what is scope resolution operator in c++

what is scope resolution operator in c++

1 year ago 41
Nature

The scope resolution operator in C++ is represented by the double colon (::) symbol. It is used to identify and specify the context to which an identifier refers, particularly by specifying a namespace or class. The operator helps to qualify hidden names so that they can still be used. Here are some common uses of the scope resolution operator in C++:

  • To access a global variable when there is a local variable with the same name.
  • To define a function outside a class.
  • To access a classs static variables.
  • To identify a member of a namespace or to identify a namespace that nominates the members namespace in a using directive.

For example, to access a global variable x when there is a local variable with the same name, we can use the scope resolution operator as follows:

int x = 10; // Local x
cout << "Value of global x is " << ::x; // Access global x using ::

In this case, the output will be "Value of global x is 0" because the global variable x is initialized to 0 by default.

To define a function outside a class, we can use the scope resolution operator as follows:

class A {
public:
    void fun(); // Declaration
};

// Definition outside class using ::
void A::fun() {
    cout << "fun() called";
}

To access a classs static variables, we can use the scope resolution operator as follows:

class Test {
public:
    static int x;
};

// Definition of static member outside class using ::
int Test::x = 5;

// Access static member using ::
cout << "Value of static x is " << Test::x;

In this case, the output will be "Value of static x is 5" because we have defined the static member x to be 5.

Overall, the scope resolution operator is a useful tool in C++ for identifying and disambiguating identifiers used in different scopes.

Read Entire Article