Write a basic C++ program which shows the use of scope resolution operator.

The scope resolution operator is represented by two colons (::) and it is used to access the entities that are defined outside the current scope. This operator is also known as the global scope operator.

Scope resolution operator is a multi-purpose operator. It can be used for following purposes:

  1. To define a member function outside the scope of class.
  2. To access a global variable when there exists a local variable with same name.
  3. To access/initialize the static member variables of a class.
  4. To distinguish the same name variables which are the members of two parent classes.
  5. To refer a class member in nested class scenario.

Tutorial 📺

Code 💻

#include<iostream.h>
#include<conio.h>

int num = 10; // Global Variable "num"

void displayNum()
{
   int num = 20;
   cout << "Local variable num = " << num;
   cout << "\n\nGlobal variable num = " << ::num << endl;
}

void main()
{
   clrscr();
   displayNum();
   getch();
}

Categorized in: