![]() |
VOOZH | about |
In C++, the scope resolution operator (::) is used to access the identifiers such as variable names and function names defined inside some other scope in the current scope. Let's take a look at an example:
GeeksforGeeks
Explanation: The std namespace contains the declaration of cout. So, to use cout, we first need to tell the compiler that it is declared inside the std namespace which is done using ::. The compiler then resolves the cout from there.
The scope resolution operator follows this general syntax:
where scope_name is the name of the scope where identifier is defined.
Following are the main applications of scope resolution operator illustrated with an example:
When a local variable shadows a global variable, meaning both have the same name, we can use the scope resolution operator :: to access the global variable.
3
It is also used to access the identifier such variables, functions and classes declared inside namespaces.
10
We use the scope resolution operator when declaring an iterator.
1
The scope resolution operator :: allows us to define a member function of a class outside the class definition.
fun() called
Static members of a class can be accessed without creating the object of the class. It is possible to access them using scope resolution operator.
1
The scope resolution operator can also be used to refer to the members of base class in a derived class especially if they have the same name.
Base class func() Derived class func()
Since the scope resolution operator (::) is important in how C++ handles variables, functions and classes, it cannot be overloaded. When the program is compiled, the compiler needs to know the purpose of every name it sees. Unlike other operators, :: lets you access global variables, classes and namespaces. If programmers could customize ::, it would bring much confusion and make the overall language approximately not secure and simple. Therefore, the scope resolution operator cannot be overloaded in C++.