liveBook · Manning

Scope resolution operator

As explained in 100 C++ Mistakes and How to Avoid Them

The C++ scope resolution operator :: qualifies a name to select a declaration from a specified namespace, class, or scope.

The scope resolution operator :: selects a name from a specified scope. It becomes useful when an inner variable shadows an outer one, or when a namespace qualifies an otherwise ambiguous name. section 9.1

Mistake: using the wrong radius

A Circle can contain a member radius, while a namespace contains another radius. Writing radius + radius uses the same visible name twice; writing radius + global::radius explicitly combines the member and namespace values. Likewise, this->radius distinguishes the member from a setter parameter named radius. section 9.1

Listing 9.3 Identical variable names distinguished by a namespace
namespace global {                                            #1
    double radius = 1.0;
};
class Circle {
private:
    double radius;
public:
    Circle(double radius) : radius(radius) {}
    void setRadius(double radius) {
        if (radius < 0)
            throw std::invalid_argument("negative radius");
        this->radius = radius;                                #2
    }
    double sum() const {
        return radius + global::radius;                       #3
    }
    double getRadius() const { return radius; }
};
 
int main() {
    Circle c(3);
    std::cout << "radius is " << c.getRadius() << '\n';
    std::cout << "enlarged radius is " << c.sum() << '\n';
    return 0;
}

Compare namespace qualification, this-> member qualification, and repeated parameter/member names in one Circle example. section 9.1

Namespace constants

A named namespace keeps a constant distinct from local variables: Constants::e qualifies e before it is passed to std::pow. section 9.1

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Defines scope and shadowing, then demonstrates qualification; it stops short of a broader operator reference.
Examples
Uses Circle radius members, global::radius, this->radius, and Constants::e in qualified expressions.
What it assumes
Teaches variable declarations, scope boundaries, and shadowing before applying qualification.
What you can do after
Apply it via qualified C++ names when shadowing or namespace collisions make the intended declaration unclear.
How it connects
Connects variable shadowing with namespaces, global variables, class members, and local variables.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.