In C++, the scope resolution operator (::) is used to define and access members of a class, namespace, or
global variables when there is ambiguity or to specify the scope explicitly. Here's how it works in the
context of classes:
1. Accessing Class Members
The scope resolution operator is used to define member functions of a class outside the class definition.
Copy code
#include <iostream>
using namespace std;
class MyClass {
public:
void display(); // Declaration of member function
};
// Definition of member function using scope resolution operator
void MyClass::display() {
cout << "Hello from MyClass!" << endl;
int main() {
MyClass obj;
obj.display(); // Calls the member function
return 0;
}
2. Accessing Static Members
Static members belong to the class rather than any specific object. The scope resolution operator is used
to access or define them.
Copy code
#include <iostream>
using namespace std;
class MyClass {
public:
static int count; // Static member declaration
static void showCount(); // Static member function declaration
};
// Definition of static member
int MyClass::count = 0;
// Definition of static member function
void MyClass::showCount() {
cout << "Count: " << count << endl;
int main() {
MyClass::count = 5; // Access static member using scope resolution
MyClass::showCount(); // Call static member function
return 0;
3. Accessing Global Variables
If a local variable shadows a global variable, the scope resolution operator can be used to access the
global variable.
Copy code
#include <iostream>
using namespace std;
int x = 10; // Global variable
int main() {
int x = 20; // Local variable
cout << "Local x: " << x << endl;
cout << "Global x: " << ::x << endl; // Access global variable
return 0;
4. Nested Classes
The scope resolution operator is also used to define or access members of nested classes.
Copy code
#include <iostream>
using namespace std;
class Outer {
public:
class Inner {
public:
void display() {
cout << "Inside Inner class!" << endl;
};
};
int main() {
Outer::Inner obj; // Access nested class using scope resolution
obj.display();
return 0;
Key Points:
The scope resolution operator cannot be overloaded.
It is essential for resolving ambiguities in cases where multiple scopes have variables or functions with
the same name.
It is also used to access members of namespaces and nested classes.
This operator is a powerful tool in C++ for managing scope and ensuring clarity in code.