• Home
  • When to use scope resolution operator in C++?

When to use scope resolution operator in C++?

The scope resolution operator (::) is used in C++ in the following situations:

To access a member of a class from outside the class: The scope resolution operator is used to access a member of a class from outside the class, as in the following example:

class MyClass
{
public:
int x;
};

int main()
{
MyClass obj;
obj.x = 10; // Accesses the member x of the class MyClass
return 0;
}

To access a global variable or a function declared in a namespace: The scope resolution operator can be used to access a global variable or a function that has been declared in a namespace, as in the following example:

namespace MyNamespace
{
int x;
void foo() { }
}

int main()
{
MyNamespace::x = 10; // Accesses the global variable x in the namespace MyNamespace
MyNamespace::foo(); // Calls the function foo in the namespace MyNamespace
return 0;
}

To access a member of a derived class that has been overridden by a member of the base class: The scope resolution operator can be used to access a member of a derived class that has been overridden by a member of the base class, as in the following example:

class Base
{
public:
virtual void foo() { }
};

class Derived : public Base
{
public:
void foo() { }
};

int main()
{
Derived obj;
obj.foo(); // Calls the overridden foo function in the class Derived
obj.Base::foo(); // Calls the foo function in the base class Base
return 0;
}

Overall, the scope resolution operator is an important concept in C++ programming, and it is used to specify the scope of a name and to access members of a class, variables, and functions from outside their scope.