You are here

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.

C++ programming code

  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. char c = 'a';     // global variable
  6.  
  7. int main() {
  8.   char c = 'b';   //local variable
  9.  
  10.   cout << "Local  variable: " << c << "\n";      
  11.   cout << "Global variable: " << ::c << "\n";  //using scope resolution operator
  12.  
  13.   return 0;
  14. }

Output of scope resolution operator program:
Scope resolution operator in C++ variable program output.

Scope resolution operator in class

  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class programming {
  5. public:
  6.   void output();  //function declaration
  7. };
  8.  
  9. // function definition outside the class
  10.  
  11. void programming::output() {
  12.   cout << "Function defined outside the class.\n";
  13. }
  14.  
  15. int main() {
  16.   programming x;
  17.   x.output();
  18.  
  19.   return 0;
  20. }

Output of program:
Scope resolution operator in C++ class program output.