top of page

Scope Resolution Operator (::) in C++

  • Writer: compnomics
    compnomics
  • Oct 1, 2024
  • 2 min read

The scope resolution operator (::) in C++ is used to access members of a class or namespace that are hidden by other declarations with the same name. It helps to resolve ambiguities and provides a way to access elements from different scopes.


When to Use the Scope Resolution Operator

  • Accessing Static Members: Static members of a class can be accessed using the scope resolution operator along with the class name. This is because static members belong to the class itself, not to individual objects.

  • Accessing Members of Base Classes: In inheritance, the scope resolution operator can be used to access members of the base class that are hidden by members of the derived class.

  • Accessing Members of Namespaces: If two namespaces have members with the same name, the scope resolution operator can be used to specify which namespace to access.


Examples

1. Accessing Static Members:

#include <iostream>

using namespace std;

class MyClass {
public:
    static int count;

    MyClass() {
        count++;
    }
};

int MyClass::count = 0;

int main() {
    MyClass obj1,    obj2;

    cout << "Count: " << MyClass::count << endl;

    return 0;
}

Output:

Count: 2

2. Accessing Members of Base Classes:

#include <iostream>

using namespace std;

class Animal {
public:
    void eat() {
        cout << "Animal is eating." << endl;
    }
};

class Dog : public Animal {
public:
    void bark() {
        cout << "Dog is barking."    << endl;
    }

    void eat() {
        cout << "Dog is eating dog food." << endl;
    }
};

int main() {
    Dog d;
    d.eat(); // Calls Dog::eat()
    d.Animal::eat(); // Calls Animal::eat()

    return 0;
}

Output:

Dog is eating dog food.
Animal is eating.

3. Accessing Members of Namespaces:

#include <iostream>

using namespace std;

namespace A {
    int x = 10;
}

namespace B {
    int x = 20;
}

int main() {
    cout << A::x << endl;
    cout << B::x << endl;

    return 0;
}

Output:

10
20

By understanding the scope resolution operator, you can effectively manage namespaces, access hidden members, and write more organized and maintainable C++ code.

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating
bottom of page