Sunday 25 September 2011

SCOPE RESOLUTION OPERATOR



SCOPE RESOLUTION OPERATOR

1.      In C, the global version of a variable cannot be accessed from within inner blocks. C++ resolves this problem by introducing a new operator :: called the scope resolution operator. This can be used to uncover a hidden variable. It takes following form.
:: variable-name
This operator allows access to the global version of a variable.

2.      The scope resolution operator also allows the programmer to define member functions outside their respective classes. The scope resolution operator signifies the class to which the member function belongs to.


SYNTAX:

<return_type> <class_name>::<member_function>
{
//body of the member function
}

Example 1

#include <iostream.h>
int a=10;
void main()
{
int a =15;
cout << ”\n Local a = “ << a << “Global a= ”<<::a;
::a=20;
cout<<”\n Local a= “ << a<< “Global a = “ << ::a;
}

Output:

Local a =15 Global a=10
Local a = 15 Global a =20

Example 2

#include <iostream.h>
class Shape
{
int len, br;
void setval(int, int);
void display();
};

void Shape::setval(int c, int d) // Scope resolution operator
{
len=c;
br=d;
}

void Shape::display() // Scope resolution operator
{
cout<< “Length “ << len’;
cout << “Breadh “ << br ;
}

void main()
{
Shape s1;
s1.setval(10,20);
s1.display();
}

No comments:

Post a Comment