c-plus-plus
  1. c-plus-plus-scope-resolution-operator

C++ Scope Resolution Operator

The scope resolution operator (::) in C++ is used to access global and class-level variables and functions. It allows a program to differentiate between variables or functions with the same name in different scopes.

Syntax

// accessing global variable
::variable_name

// accessing class-level variable
class_name::variable_name

// accessing class-level function
class_name::function_name()

// accessing static class-level variable
class_name::static_variable_name

// accessing static class-level function
class_name::static_function_name()

Example

#include <iostream>
using namespace std;

int x = 10;

class MyClass {
public:
    int x = 20;

    void printX() {
        cout << "class x = " << x << endl;
        cout << "global x = " << ::x << endl;
    }
};

int main() {
    MyClass obj;
    obj.printX();
    return 0;
}

Output

class x = 20
global x = 10

Explanation

In the above example, we have a global variable "x" and a class-level variable "x" with the same name. Inside the class, we use the scope resolution operator to differentiate between them. The "::" operator is used to access the global "x" while "class_name::" is used to access the class-level "x".

Use

The scope resolution operator is mainly used to access global and class-level variables and functions. It is also used to access static variables and functions in a class.

#include <iostream>
using namespace std;

class MyClass {
public:
    static int x;
    static void printX() {
        cout << "static x = " << x << endl;
    }
};

int MyClass::x = 100;

int main() {
    MyClass::printX();
    return 0;
}

In the above example, we have a static variable "x" declared in the MyClass class. We use the scope resolution operator to access it inside the static function "printX".

Important Points

  • The scope resolution operator is used to access global and class-level variables and functions.
  • The "::" operator is used to access global variables and functions.
  • "class_name::" is used to access class-level variables and functions.
  • The scope resolution operator is also used to access static variables and functions in a class.

Summary

In summary, the scope resolution operator "::" in C++ is a powerful tool for accessing different variables and functions in different scopes. It is particularly useful when dealing with naming conflicts and object-oriented programming. By using it correctly, a programmer can avoid potential bugs and improve the overall quality of their code.

Published on: