UNIT 2: SCOPE RESOLUTION OPERATOR ::
CAP202| Dr. Ajay Rastogi | Programming Domain
TO ACCESS A GLOBAL VARIABLE WHEN THERE IS A LOCAL
VARIABLE WITH SAME NAME:
#include<iostream>
using namespace std;
int x=10; // Global x
main()
{
int x = 20; // Local x
cout << "Value of global x is " << ::x;
cout << "nValue of local x is " << x;
}
TO DEFINE A FUNCTION OUTSIDE A CLASS.
#include<iostream>
using namespace std;
class lpu
{ public:
void fun();
};
void lpu::fun()
{ cout << "fun() called";
}
main()
{ lpu a;
a.fun();
}
TO ACCESS A CLASS’S STATIC VARIABLES.
#include<iostream>
using namespace std;
class Test
{ static int x;
public:
static int y;
void func()
{ cout << "Value of static x
is " << Test::x;
}
};
int Test::x = 1;
int Test::y = 2;
main()
{ Test obj;
int x = 3 ;
obj.func();
cout << "nvalue of static y
= " << Test::y;
}
REFER TO A CLASS INSIDE ANOTHER CLASS:
class outside
{ public:
int x=10;
void outclass()
{ cout<<x<<endl; }
class inside
{ public:
int y=20;
void intclass()
{ cout<<y<<endl; }
};
};
int main()
{ outside A;
A.outclass();
outside::inside B;
B.intclass();
}