Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Scope Resolution Operator in C++

Last Updated on March 29, 2023 by Prepbytes

Scope resolution operator in C++ is one of the essential operators which is used to identify and access the entities that are defined outside the current scope of a program. In simple terms, it allows a programmer to access global or namespace-level entities within a function or a class. This article discusses scope resolution operation in C++, its syntax, its purpose, and applications of scope resolution operator in C++.

What is Scope Resolution Operator in C++?

The scope resolution operator in C++ is represented by two colons (::) and is used to access entities that are defined outside the current scope of a program. This operator is also known as the global scope operator.

Let’s take an example to understand more clearly, suppose we have two integer variables defined as valuation, one is declared globally and one locally. Both integer variables have different scopes and to access the global variable valuation inside the local scope, the resolution operator "::" is used as follows:

Code Implementation

#include<bits/stdc++.h>
using namespace std;

// global variable
int valuation = 1000000;

int main(){
   // local variable
   int valuation = 100000;
   
   cout << "Value of the variable valuation in local scope: " << valuation <<"\n";
   
   cout << "Value of the variable valuation in Global scope: " << ::valuation << "\n";
   
   return 0;
}

Output:

Value of the variable valuation in local scope: 100000
Value of the variable valuation in Global scope: 1000000

Explanation: In this example, the local variable ‘valuation’ declared in the main function hides the global declaration of the variable ‘valuation’, which is accessed by using the scope resolution operator "::" with the identifier ‘valuation’.

Syntax of Scope Resolution Operator in C++

The scope resolution operator in C++ is represented by two consecutive colons (::) and is used to access global variables, class members, and namespace members.

The basic syntax of the scope resolution operator in C++ is:

::

Here, < namespace_or_class_name> can be the name of a namespace or class, and < member_name> can be the name of a global variable, class member, or namespace member.

Purpose of Scope Resolution Operator in C++

The scope resolution operator in C++ serves the following purpose.

  1. To access a global variable when there is a local variable with the same name
    In C++, when there is a local variable with the same name as a global variable, we can use the scope resolution operator to access the global variable from within the scope of the local variable. Let’s look at an example to see how to implement this using the scope resolution operator in C++.

    Code Implementation:

    #include <iostream>
    using namespace std;
    
    int x = 10; // Global variable
    
    int main() {
      int x = 20; // Local variable
      cout << "Local x: " << x << endl; 
      cout << "Global x: " << ::x << endl;
      return 0;
    }

    Output:

    Local x: 20
    Global x: 10

    Explanation: In this example, we have defined a global variable called x with a value of 10. Inside the main function, we have defined a local variable also called x with a value of 20. When we use the identifier x without any qualification, it refers to the local variable. However, when we use the scope resolution operator followed by the unary scope resolution operator (::), it refers to the global variable.

  2. To define a function outside a class
    In C++, we can define a function outside a class using the scope resolution operator. Let’s look at an example to see how to implement this using the scope resolution operator in C++.

    Code Implementation:

    #include<bits/stdc++.h>
    using namespace std;
    
    class Student{
        
        public:
           void printInformation();
           void printCollegeName();
    };
    
    // Defining the member functions outside the class.
    void Student::printInformation(){
        cout << "Name: XYZ\n";
        cout << "BRANCH: Information Technology\n";
    }
    
    void Student::printCollegeName(){
      cout << "CollegeName: IIIT Allahabad\n";
    }
    
    int main(){
       Student PrepBuddy;
       PrepBuddy.printInformation();
       PrepBuddy.printCollegeName();
       return 0;
    }

    Output:

    Name: XYZ
    BRANCH: Information Technology
    CollegeName: IIIT Allahabad

    Explanation: In this example, we have defined a class called ‘Student’ that contains two functions. We have declared the functions inside the class using the function prototype, but the actual definition of the functions is outside the class.

    To define the function outside the class, we use the scope resolution operator and the class name followed by the function name. In this case, we define the printInformation function outside the class using void Student::printInformation().

  3. To Access a Class’s Static Variables
    In C++, we can access a class’s static variables using the scope resolution operator. Let’s look at an example to see how to implement this using the scope resolution operator in C++.

    Code Implementation:

    #include <iostream>
    using namespace std;
    
    class MyClass {
      public:
        static int count;
    };
    
    int MyClass::count = 25;
    
    int main() {
      MyClass obj1;
      cout << "Count: " << MyClass::count << endl;
      return 0;
    }

    Output:

    Count: 25

    Explanation: In this example, we have defined a class called MyClass that contains a static variable called count. To define the static variable, we use the scope resolution operator and the class name followed by the variable name. We initialize the variable to 25.

    To access the static variable, we use the class name followed by the scope resolution operator and the variable name, like this: MyClass::count. We can access the static variable from anywhere in the program, including outside the class and from different objects of the class.

  4. In the Case of Multiple Inheritance
    We can inherit many classes into a single class and access the members of those inherited classes. Let’s look at an example to see how to implement this using the scope resolution operator in C++.

    Code Implementation:

    #include <iostream>
    using namespace std;
    
    class Base1 {
    public:
        void func() {
            cout << "This is Base1's function" << endl;
        }
    };
    
    class Base2 {
    public:
        void func() {
            cout << "This is Base2's function" << endl;
        }
    };
    
    class Derived : public Base1, public Base2 {
    public:
        void call_function() {
            Base1::func(); 
            Base2::func(); 
        }
    };
    
    int main() {
        Derived d;
        d.call_function();
    
        return 0;
    }

    Output:

    This is Base1's function
    This is Base2's function

    Explanation: In this example, we have two base classes, Base1 and Base2, and a derived class, Derived, which inherits from both base classes. Both base classes have a member function named func.

    In the call_function() function of the Derived class, we use the scope resolution operator to call the func function of both Base1 and Base2. By specifying the base class name before the :: operator, we can call the specific version of the func function that we want.

  5. For Namespace
    In a single scope, we can only create one variable with a given name since creating another variable with the same name will result in an error, but we can use namespaces to create several variables and functions with the same name and access those variables. Let’s look at an example to see how we can implement this using the scope resolution operator in C++.

    Code Implementation:

    #include<bits/stdc++.h>
    using namespace std;
    
    int PrepNum = 150;
    
    // First namespace
    namespace first{
         int PrepNum = 120;
    }
    
    // Second namespace
    namespace second{
         int PrepNum = 190;
         void print(){
             cout << "\nTwice of the value PrepNum is: " << 2*PrepNum << " ";
         }
    }
    
    int main(){
        int PrepNum = 100;
        
        cout << "Value of PrepNum in local scope: " << PrepNum << "\n";
        cout << "Value of PrepNum in global scope: " << ::PrepNum << "\n";
        cout << "Value of PrepNum in first namespace: " << first::PrepNum << "\n";
        cout << "Value of PrepNum in second namespace: "; 
        second::print();
        return 0;
    }

    Output:

    Value of PrepNum in local scope: 100
    Value of PrepNum in global scope: 150
    Value of PrepNum in first namespace: 120
    Value of PrepNum in second namespace: 
    Twice of the value PrepNum is: 380 

    Explanation: In this example, scope resolution operator accesses many scopes here. As we can see, the scope resolution operator is used to access PrepNum in the first and second namespaces. In the second line of the program, we put "using namespace std," which simply implies that we are using namespace std, i.e., standard and that we can use all functions and variables in the std namespace.

  6. To Refer to a Class Inside Another Class
    we can access the class present inside the other class and also its member functions. Let’s look at an example to see how we can implement this using the scope resolution operator in C++.

    Code Implementation:

    #include <iostream>
    using namespace std;
    
    class outside {
    public:
        int x;
        class inside {
        public:
            int x;
            static int y;
            int foo();
        };
    };
    int outside::inside::y = 150;
    
    int main()
    {
        outside A;
        outside::inside B;
        cout<<"value of static variable y is "<<B.y<<endl;
        return 0;
    }

    Output:

    value of static variable y is 150

    Explanation: In this example, we have a class named ‘outside’ that contains an inner class named ‘inner’. The inner class has a static variable named y whose value is printed using the scope resolution operator.

Applications of Scope Resolution Operator in C++

Here are some applications of the scope resolution operator in C++:

  1. Accessing global variables from within a function or method that has a local variable with the same name.
  2. Defining and implementing class member functions outside the class definition.
  3. Accessing static variables of a class from anywhere in the program, including outside the class and from different objects of the class.
  4. Accessing nested classes and their members.
  5. Resolving namespace conflicts when two or more namespaces have the same identifier.
  6. Accessing members of a base class from a derived class that has overridden the member.

Conclusion
In conclusion, the scope resolution operator in C++ allows us to access variables, functions, and members from different scopes and namespaces. It is a powerful feature that enhances the readability, maintainability, and organization of our code. By using the scope resolution operator, we can avoid naming conflicts, access static variables, define and implement class member functions outside the class, and access nested classes and their members.

FAQs

Here are some frequently asked questions about the scope resolution operator in C++.

Q1: Can I access nested classes and their members using the scope resolution operator in C++?
A: Yes, you can use the scope resolution operator in C++ to access nested classes and their members.

Q2: Can I access members of a base class from a derived class that has overridden the member?
A: Yes, you can use the scope resolution operator to access members of a base class from a derived class that has overridden the member.

Q3: Is the scope resolution operator in C++ overloaded?
A: No, the scope resolution operator in C++ cannot be overloaded.

Q4: Can I use the scope resolution operator with non-static members of a class?
A: No, the scope resolution operator can only be used with static members of a class.

Q5: Can I use the scope resolution operator in C++ to access members of an object?
A: No, you cannot use the scope resolution operator in C++ to access members of an object. You need to use the dot operator (.) or the arrow operator (->) instead.

Q6: Can I use the scope resolution operator in C++ to access identifiers in the same scope or namespace?
A: No, the scope resolution operator in C++ is not needed to access identifiers in the same scope or namespace.

Leave a Reply

Your email address will not be published. Required fields are marked *