Explain (scope resolution operator) :: operator with an example - C++

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.
- Example :
….
….
{
   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.
- Example :
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
}

When do you use :: Operator in C++?

- :: is the scope resolution operator. When local variable and global variable are having same name, local variable gets the priority. C++ allows flexibility of accessing both the variables through a scope resolution operator.
What is const qualifier? - C++
What is const qualifier? - The qualifier const can be applied to the declaration of any variable to indicate that its value will not be changed.....
Describe Selection – if and switch using C++
Describe Selection – if and switch using C++ - if is decision making control and its general for is:...
Explain Loops – While loop, Do-while loop, for loop
Explain Loops – While loop, Do-while loop, for loop - Loops are used to carry out certain instruction(s) in continuation for a fixed no of times.....
Post your comment