
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 unary scope operator if a namespace scope or global scope name is hidden by a particular declaration of an equivalent 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.
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 Questions & Answers
- C++ Scope resolution operator
- 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++
- Why does C++ need the scope resolution operator?
- Where do we use scope Resolution Operator (::) in C#?
- What is the use of scope resolution operator in C++?
- Scope Rules in C
- Scope of Variables in C++
- Scope of Variables in C#
- C++ Scope of Variables
- Variables, their types, and Scope in C++
- Avoid Scope Creep: Control Your Project Scope
- Explain scope of a variable in C language.