Friday, February 5, 2010

Explain :: operator with an example.

:: Operator: ‘::’ is known as Scope Resolution Operator. C++ is a block structured language. Different program modules are written in various blocks. Same variable name can be used in different blocks. Scope of a variable extends from the point of declaration to the end of the block. A variable declared inside a block is ‘local’ variable. Blocks in C++ are often nested.
e.g.
….
….
{
           int x = 10;
           ….
           ….
           {
                  int x = 20;
                  …..
                  ….
           }
           ….
}
The declaration of the inner block hides the declaration of same variable in outer block. This means, within the inner block, the variable x will refer to the data object declared therein. To access the global version of the variable, C++ provides scope resolution operator.
In the above example, x has a value of 20 but ::x has value 10.
Similarly, this operator is used when a member function is defined outside the class
e.g.
Class MyClass
{
int n1, n2;
public:
{
void func1();                     ---------Function Declaration
}
};
public void MyClass::func1() ---Use of Scope Resolution Operator to write  
                                                        function definition outside class definition
{
               // Function Code 
}

0 Comments: