The Wayback Machine - https://web.archive.org/web/20240907074357/https://www.geeksforgeeks.org/scope-resolution-operator-in-c/
Open In App

Scope resolution operator in C++

Last Updated : 18 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In C++, the scope resolution operator is ::. It is used for the following purposes.

1) To access a global variable when there is a local variable with same name: 

CPP
// C++ program to show that we can access a global variable
// using scope resolution operator :: when there is a local 
// variable with same name 
#include<iostream> 
using namespace std;

int x; // Global x

int main()
{
int x = 10; // Local x
cout << "Value of global x is " << ::x;
cout << "\nValue of local x is " << x; 
return 0;
}

Output
Value of global x is 0
Value of local x is 10

2) To define a function outside a class. 

CPP
// C++ program to show that scope resolution operator :: is
// used to define a function outside a class
#include <iostream>
using namespace std;

class A {
public:
    // Only declaration
    void fun();
};

// Definition outside class using ::
void A::fun() { cout << "fun() called"; }

int main()
{
    A a;
    a.fun();
    return 0;
}

Output
fun() called

3) To access a class’s static variables. 

CPP
// C++ program to show that :: can be used to access static
// members when there is a local variable with same name
#include<iostream>
using namespace std;

class Test
{
    static int x; 
public:
    static int y; 

    // Local parameter 'x' hides class member
    // 'x', but we can access it using ::
    void func(int x) 
    { 
    // We can access class's static variable
    // even if there is a local variable
    cout << "Value of static x is " << Test::x;

    cout << "\nValue of local x is " << x; 
    }
};

// In C++, static members must be explicitly defined 
// like this
int Test::x = 1;
int Test::y = 2;

int main()
{
    Test obj;
    int x = 3 ;
    obj.func(x);

    cout << "\nTest::y = " << Test::y;

    return 0;
}

Output
Value of static x is 1
Value of local x is 3
Test::y = 2

4) In case of multiple Inheritance: If the same variable name exists in two ancestor classes, we can use scope resolution operator to distinguish. 

CPP
// Use of scope resolution operator in multiple inheritance.
#include<iostream>
using namespace std;

class A
{
protected:
    int x;
public:
    A() { x = 10; }
};

class B
{
protected:
    int x;
public:
    B() { x = 20; }
};

class C: public A, public B
{
public:
void fun()
{
    cout << "A's x is " << A::x;
    cout << "\nB's x is " << B::x;
}
};

int main()
{
    C c;
    c.fun();
    return 0;
}

Output
A's x is 10
B's x is 20

5) For namespace If a class having the same name exists inside two namespaces we can use the namespace name with the scope resolution operator to refer that class without any conflicts

C++
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
#define nline "\n"

// Global Declarations

string name1 = "GFG";
string favlang = "python";
string companyName = "GFG_2.0";

// You can also do the same thing in classes as we did in
// our struct example

class Developer {
public:
    string name = "krishna";
    string favLang = "c++";
    string company = "GFG";

    // Accessing Global Declarations

    Developer(string favlang, string company)
        : favLang(favlang)
        , company(companyName)
    {
    }
};

int main()
{
    Developer obj = Developer("python", "GFG");
    cout << "favourite Language : " << obj.favLang << endl;
    cout << "company Name : " << obj.company << nline;
}

Output
favourite Language : python
company Name : GFG_2.0

6) Refer to a class inside another class: If a class exists inside another class we can use the nesting class to refer the nested class using the scope resolution operator

CPP
// Use of scope resolution class inside another class.
#include <iostream>
using namespace std;

class outside {
public:
    int x;
    class inside {
    public:
        int x;
        static int y;
        int foo();
    };
};
int outside::inside::y = 5;

int main()
{
    outside A;
    outside::inside B;
}

7) Refer to a member of the base class in the derived object: In the case of having the same method in both the base and derived classes, we could refer to each by the scope resolution operator as below.

C++
// Refer to a member of the base class in the derived object.
#include <iostream>

class Base {
public:
    void func()
    {
        std::cout << "This is Base class" << std::endl;
    }
};

class Derived : public Base {
public:
    void func()
    {
        std::cout << "This is Derived class" << std::endl;
    }
};

int main()
{
    Derived obj;
    obj.Base::func();
    obj.func();
    return 0;
}

Output
This is Base class
This is Derived class




Previous Article
Next Article

Similar Reads

Scope Resolution Operator vs this pointer in C++
Scope resolution operator is for accessing static or class members and this pointer is for accessing object members when there is a local variable with the same name. Consider below C++ program: C/C++ Code // C++ program to show that local parameters hide // class members #include &lt;iostream&gt; using namespace std; class Test { int a; public: Te
3 min read
deque::operator= and deque::operator[] in C++ STL
Deque or Double ended queues are sequence containers with the feature of expansion and contraction on both the ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. deque::operator= This operator
4 min read
Operator Overloading '&lt;&lt;' and '&gt;&gt;' operator in a linked list class
Prerequisite: Operator Overloading in C++, Linked List in C++ C++ comes with libraries that provide ways for performing Input and Output. In C++, Input and Output are performed as a sequence of bytes, also known as streams. Input and Output stream are managed by the iostream library. cin and cout are the standard objects for the input stream and ou
4 min read
Why overriding both the global new operator and the class-specific operator is not ambiguous?
The below section deals about overload resolution as it helps in the fundamentals of overloading and overriding. Predict the output: C/C++ Code #include &lt;iostream&gt; using namespace std; class Gfg { public: void printHello() { cout &lt;&lt; &quot;hello gfg-class specific&quot; &lt;&lt; endl; } }; void printHello() { cout &lt;&lt; &quot;hello gf
5 min read
vector::operator= and vector::operator[ ] in C++ STL
Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::operator=This operator is used to assign new contents to the container by replacing the existing contents. It also modifies the size according to the new
4 min read
Scope of Variables in C++
In general, the scope is defined as the extent up to which something can be worked with. In programming also the scope of a variable is defined as the extent of the program code within which the variable can be accessed or declared or worked with. There are mainly two types of variable scopes: Local VariablesGlobal Variables Now let's understand ea
5 min read
Operands for sizeof operator
The sizeof operator is used to return the size of its operand, in bytes. This operator always precedes its operand. The operand either may be a data-type or an expression. Let's look at both the operands through proper examples. type-name: The type-name must be specified in parentheses. sizeof(type - name) Let's look at the code: C/C++ Code #includ
2 min read
array::operator[ ] in C++ STL
Array classes are generally more efficient, light-weight, and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays. array::operator[] This operator is used to reference the element present at position given inside the operator. It is similar to the at() function, the only diffe
2 min read
list::operator= in C++ STL
Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. list::operator= This operator is used to assign new contents to the container by replacing the exis
2 min read
forward_list::operator= in C++ STL
Forward list in STL implements singly linked list. Introduced from C++11, forward lists are useful than other containers for insertion, removal and moving operations (like sort) and allows time constant insertion and removal of elements.It differs from the list by the fact that forward list keeps track of the location of only next element while lis
2 min read
map::operator[] in C++ STL
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values. map::operator[] This operator is used to reference the element present at position given inside the operator. It is similar to the at() function, the only difference is that the at(
2 min read
multiset::operator= in C++ STL
Multisets are a type of associative containers similar to set, with an exception that multiple elements can have same values. multiset::operator= This operator is used to assign new contents to the container by replacing the existing contents. It also modifies the size according to the new contents.Syntax : multisetname1 = (multisetname2) Parameter
3 min read
multimap::operator= in C++ STL
multimap::operator= is used to assign new contents to the container by replacing the existing contents. It also modifies the size according to the new contents. Syntax:- multimap1 = (multimap2) Parameters : Another container of the same type. Result : Assign the contents of the container passed as parameter to the container written on left side of
2 min read
unordered_map operator= in C++ STL
The ‘=’ is an operator in C++ STL which copies (or moves) an unordered_map to another unordered_map and unordered_map::operator= is the corresponding operator function. There are three versions of this function. The first version takes reference of an unordered_map as an argument and copies it to an unordered_map. The second version performs a move
2 min read
unordered_multiset operator = in C++ STL
The ‘=’ is an operator in C++ STL which copies (or moves) an unordered_multiset to another unordered_multiset and unordered_multiset::operator= is the corresponding operator function. There are three versions of this function: The first version takes reference of an unordered_multiset as an argument and copies it to an unordered_multiset. Syntax:um
2 min read
alignof operator in C++
In C++11 the alignof operator used to returns the alignment, in bytes of the specified type. Syntax: alignof(type) Syntax Explanation: alignof: operator returns the alignment in byte, required for instances of type, which type is either complete type, array type or a reference type. array type: alignment requirement of the element type is returned.
2 min read
bitset operator[] in C++ STL
bitset::operator[] is a built-in function in C++ STL which is used to assign value to any index of a bitset. Syntax: bitset_operator[index] = value Parameter: The parameter index specifies the position at which the value is to be assigned. Return Value: The function returns the value to the bit at the index. Below programs illustrate the bitset::op
2 min read
multimap operator = in C++ STL
The multimap::operator= is a built in C++ STL which assigns new contents to the container, replacing its current content. Syntax: multimap1_name = multimap2_name Parameters: The multimap on the left is the container in which the multimap on the right is to be assigned by destroying the elements of multimap1. Return Value: This function does not ret
2 min read
map operator= in C++ STL
The map::operator= is a built function in C++ STL which assigns contents of a container to a different container, replacing its current content. Syntax: map1_name = map2_name Parameters: The map on the left is the container in which the map on the right is to be assigned by destroying the elements of map1. Return Value: This function does not retur
2 min read
unordered_multimap operator= in C++
The unordered_multimap::operator= is a built-in function in C++ STL which does three types of tasks which are explained below. Syntax (copying elements from different container) : unordered_multimap_name1 operator= (unordered_multimap_name2)Parameters: The function does not accepts any parameter. The container to the right is the one from which the
4 min read
match_results operator[] in C++ STL
The match_results::operator[] is a built function in C++ which used to get the i-th match in the match_result object. It gives the reference to the match at the position given inside the operator.Syntax: smatch_name[N] Note: smatch_name is an object of match_results class. Parameters: It accepts a single parameter N which specifies the Match number
2 min read
match_results operator= in C++
The match_results::operator= is used to replace all the matches in a smatch object with new matches from another smatch object.Syntax: smatch_name1 = (smatch_name2) Note: smatch_name is an object of match_results class. Parameters: The smatch object on the right side gets copied to the one at the left side. Return Value: It does not return anything
2 min read
unordered_set operator= in C++ STL
The '=' is an operator in C++ STL which copies (or moves) an unordered_set to another unordered_set and unordered_set::operator= is the corresponding operator function. There are three versions of this function. The first version takes reference of an unordered_set as an argument and copies it to an unordered_set.The second version performs a move
2 min read
C++ | Nested Ternary Operator
Ternary operator also known as conditional operator uses three operands to perform operation. Syntax : op1 ? op2 : op3; Nested Ternary operator: Ternary operator can be nested. A nested ternary operator can have many forms like : a ? b : ca ? b: c ? d : e ? f : g ? h : ia ? b ? c : d : e Let us understand the syntaxes one by one : a ? b : c =&gt; T
5 min read
set operator= in C++ STL
The ‘=’ is an operator in C++ STL which copies (or moves) a set to another set and set::operator= is the corresponding operator function. There are three versions of this function: The first version takes reference of an set as an argument and copies it to an set. Syntax: ums1.operator=(set &amp;set2) Parameters: The first version takes the referen
2 min read
unordered_set operator!= in C++ STL
The != is a relational operator in C++ STL which compares the equality and inequality between unordered_set containers. The Comparison is done in the following procedure: First, the sizes are compared.Then, each element in one of the containers is looked for in the other. Syntax: unordered_set1 != unordered_set2 Parameters: This method takes the tw
2 min read
unordered_set == operator in C++ STL
The ‘==’ is an operator in C++ STL performs equality comparison operation between two unordered sets and unordered_set::operator== is the corresponding operator function for the same. Syntax: (unordered_set &amp;uset1 == unordered_set &amp;uset2) Parameters: This operator function takes reference of two unordered sets uset1 and uset2 as parameters
2 min read
unordered_map operator[] in C++ STL
The std::unordered_map::operator[] is a built in function in C++ STL which returns the reference of value if key matches in the container. If no key is found then it inserts that key into container. Syntax: mapped_type&amp; operator[](key_type&amp;&amp; k); Parameter: It takes parameter as key whose mapped value is accessed. Return type: Returns a
2 min read
unordered_multimap operator= in C++ STL
The ‘=’ is an operator in C++ STL which copies (or moves) an unordered_multimap to another unordered_multimap and unordered_multimap::operator= is the corresponding operator function. There are three versions of this function. The first version takes reference of an unordered_multimap as an argument and copies it to an unordered_multimap. The secon
2 min read
Increment Operator Behavior When Passed as Function Parameters in C++
In C++, an increment operator is used to increment the value of the variable by 1. The symbol ++ is used to represent the increment operator. There are two types of increment operators: Pre-Increment Operator: This form of increment operator increases the value of the variable by 1 before assigning it to the variable.Post-Increment Operator: This f
3 min read
Article Tags :
Practice Tags :