Mon Aug 22 2022
Scope resolution operator in C++
Scope resolution operator (::) in C++ programming language is used to define a function outside a class or when we want to use a global variable but also has a local variable with the same name. It is usually a binary operator which takes two inputs i.e. one before it and one after it. It is used to associate a part of the program to a particular scope which means that it can be used to recognize or relate any variable, function etc to another part of the program.
You can use the unary scope operator if a namespace scope or global scope name is hidden by an explicit declaration of the same name in a block or class. You can also use the class scope operator to qualify class names or class member names. If a class member name is hidden, you can use it by qualifying it with its class name and the class scope operator.
Syntax of Scope resolution operator
class_name :: identifier
namespace :: identifier
Example
Output
Local variable: b
Global variable: a
Why do we use it?
It is used when we need to specify to which scope a particular identifier belongs to.
Example
When we use, A::a, we tell the compiler that we want to access the variable ‘a’ which is present in the scope of structure 'A'.
When we use ::a, we tell the compiler that we want to access the global variable ‘a’ (mentioning no scope before the scope resolution operator signifies we want to access something from the global scope).
When we simply use ‘a’, we inform the compiler that we want to access the variable in the local scope of main() function.
If we don’t use the scope resolution operator, every time we mention ‘a’, it will by default refer to the main() scope. So, it helps when we want to access entities from a different scope. It was just a simple example. The scope resolution operator has many applications which you will become familiar as you go deep into C++.