What is the meaning of prepended double colon “::” in C++?

C++ProgrammingServer Side Programming

The prepended double colon is also known as the scope resolution operator. Some of the uses of this operator are given as follows.

Define a function outside a class

The scope resolution operator can be used to define a function outside a class. A program that demonstrates this is given as follows.

Example

 Live Demo

#include<iostream>
using namespace std;
class Example {
   int num;
   public:
   Example() {
      num = 10;
   }
   void display();
};
void Example::display() {
   cout << "The value of num is: "<<num;;
}
int main() {
   Example obj;
   obj.display();
   return 0;
}

Output

The output of the above program is as follows.

The value of num is: 10

Access a global variable when there is also a local variable with the same name

The scope resolution operator can be used to access a global variable when there is also a local variable with the same name. A program that demonstrates this is given as follows.

Example

 Live Demo

#include<iostream>
using namespace std;
int num = 7;
int main() {
   int num = 3;
   cout << "Value of local variable num is: " << num;
   cout << "\nValue of global variable num is: " << ::num;
   return 0;
}

Output

The output of the above program is as follows.

Value of local variable num is: 3
Value of global variable num is: 7
raja
Published on 21-Nov-2018 12:17:56
Advertisements