Scope Resolution in Class in C++

The scope resolution operator in C++ programming is used to define a function and access the static variables of a class from outside that class by using (::) operator.

Program Calling Two Classes Functions

Program

#include<iostream.h>
#include<conio.h>
class cls //'cls' is name of Class.
{
public:
cls()
{
cout<<"This is Default Constructor of Class cls"<<endl;
}
void fun()
{
cout<<"This is Simple Function of Class cls"<<endl;
}
};
class cls2 //'cls2' is name of another Class.
{
public:
cls2()
{
cout<<"This is Default Constructor of Class cls2"<<endl;
}
void fun()
{
cout<<"This is Simple Function of Class cls2"<<endl;
}
};
void main()
{
 cls obj; //'obj' is object of class 'cls'.
 cls2 obj2; //'obj2' is object of class 'cls2'.
 obj.fun();
 obj2.fun();
 getch();
}
Output
This is Default Constructor of Class cls
This is Default Constructor of Class cls2
This is Simple Function of Class cls
This is Simple Function of Class cls2

Program using Scope Resolution Operator

Program

#include<iostream.h>
#include<conio.h>
class cls
{
private:
int a,b;
public:
cls(int x, int y)
{
a = x;
b = y;
}
void show(); //declaring function 'show()'.
};
void main()
{  //calling and passing arguments to parameters and 'obj' is
cls obj(5, 6); //object of class 'cls'.
obj.show(); //calling 'show()' function.
getch();
}
void cls::show() //this is Scope Resolution.
{
cout<<"a is: "<<a<<endl;
cout<<"b is: "<<b<<endl;
}
Output
a is: 5
b is: 6

Program Counting Object of Class

Program

#include<iostream.h>
#include<conio.h>
class cls
{
private:
static int num; //'num' used for static integer value.
public:
cls() //this is default constructor.
{
num++; //adding 1 to 'num' value.
}
void show()
{
cout<<num<<" Objects is Declared"<<endl;
}
};
int cls::num; //this is Scope Resolution.
void main()
{
cls a, b, c, d, e; //'a, b, c, d and e' is objects of class 'cls'.
e.show(); //calling 'show()' function.
getch();
}
Output
5 Objects is Declared