- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Why does C++ need the scope resolution operator?
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 unary scope operator if a namespace scope or global scope name is hidden by an explicit declaration of the same name in 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
- C++ Scope resolution operator
- Scope resolution operator in C++
- PHP Scope Resolution Operator (::)
- What is the scope resolution operator in C#?
- Scope Resolution Operator Versus this pointer in C++?
- Scope Resolution Operator vs this pointer in C++
- What is the use of scope resolution operator in C++?
- Where do we use scope Resolution Operator (::) in C#?
- Why does the JavaScript need to start with “;”?
- Why does the soil need leveling? Give at least 4 points.
- Why does one need a mentor in life to grow?
- Does JavaScript support block scope?
- JavaScript : Why does % operator work on strings? - (Type Coercion)
- Does the plant need food?
- How does the Comma Operator work in C++
