scop resolution
scop resolution
The scope resolution operator is used to reference the global variable or member
function that is out of scope. Therefore, we use the scope resolution operator to
access the hidden variable or function of a program. The operator is represented as
the double colon (::) symbol.
For example, when the global and local variable or function has the same
name in a program, and when we call the variable, by default it only
accesses the inner or local variable without calling the global variable. In this
way, it hides the global variable or function. To overcome this situation, we
use the scope resolution operator to fetch a program's hidden variable or
function.
#include <iostream>
using namespace std;
// declare global variable
int num = 50;
int main ()
{
// declare local variable
int num = 100;
Output
#include <iostream>
using namespace std;
class Operate
{
public:
void fun(); // declaration of the member function
};
// define the member function outside the class.
void Operate::fun() /* return_type Class_Name::function_name */
{
cout << " It is the member function of the class. ";
}
int main ()
{
// create an object of the class Operate
Operate op;
op.fun();
return 0;
}
Output
#include <iostream>
int main ()
{
int num = 0;
Output
#include <iostream>
using namespace std;
class Parent
{
static int n1;
public:
static int n2; // The class member can be accessed using the scope re
solution operator.
void fun1 ( int n1)
{ // n1 is accessed by the scope resolution operator (:: )
cout << " The value of the static integer n1: " << Parent::n1;
cout << " \n The value of the local variable n1: " << n1;
}
};
// define a static member explicitly using :: operator
int Parent::n1 = 5; // declare the value of the variable n1
int Parent::n2 = 10;
int main ()
{
Parent b;
int n1 = 15;
b.fun1 (n1);
cout << " \n The value of the Base::n2 = " << Parent::n2;
return 0;
}
Output
#include <iostream>
using namespace std;
class ABC
{
public:
// declare static member function
static int fun()
{
cout << " \n Use scope resolution operator to access the static membe
r. ";
}
};
int main ()
{
// class_name :: function name
ABC :: fun ();
return 0;
}
Output
#include <iostream>
using namespace std;
class ABC
{
// declare access specifier
public:
void test ()
{
cout << " \n It is the test() function of the ABC class. ";
}
};
// derive the functionality or member function of the base class
class child : public ABC
{
public:
void test()
{
ABC::test();
cout << " \n It is the test() function of the child class. ";
}
};
int main ()
{
// create object of the derived class
child ch;
ch.test();
return 0;
}
Output
It is the test() function of the ABC class.
It is the test() function of the child class.