
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
What is the use of scope resolution operator in C++?
The :: (scope resolution) operator is used to get hidden names due to variable scopes so that you can still use them. The scope resolution operator can be used as both unary and binary
You can use the single scope operator if a namespace scope or global scope name is hidden by a certain declaration of a similar name during a block or class. For example, if you have a global variable of name my_var and a local variable of name my_var, to access global my_var, you'll need to use the scope resolution operator. For example,
Example
#include <iostream> using namespace std; int my_var = 0; int main(void) { int my_var = 0; ::my_var = 1; // set global my_var to 1 my_var = 2; // set local my_var to 2 cout << ::my_var << ", " << my_var; return 0; }
Output
This will give the output −
1, 2
The declaration of my_var declared in the main function hides the integer named my_var declared in global namespace scope. The statement ::my_var = 1 accesses the variable named my_var declared in global namespace scope.
You can also use the scope resolution operator to use class names or class member names. If a class member name is hidden, you can use it by prefixing it with its class name and the class scope operator. For example,
Example
#include <iostream> using namespace std; class X { public: static int count; }; int X::count = 10; // define static data member int main () { int X = 0; // hides class type X cout << X::count << endl; // use static member of class X }
Output
This will give the output −
10
- Related Articles
- What is the scope resolution operator in C#?
- Where do we use scope Resolution Operator (::) in C#?
- C++ Scope resolution operator
- PHP Scope Resolution Operator (::)
- Scope resolution operator in C++
- Why does C++ need the scope resolution operator?
- Scope Resolution Operator Versus this pointer in C++?
- Scope Resolution Operator vs this pointer in C++
- What is the use of RLIKE operator in MySQL?
- What is the use of sizeof Operator in C#?
- What is the use of tilde operator (~) in R?
- What is the use of SOUNDS LIKE operator in MySQL?
- What is the use of MySQL NOT LIKE operator?
- What is the use of MySQL SOUNDS LIKE operator?
- What is the use of MySQL IS and IS NOT operator?
