Scope Resolution Operator
Scope Resolution Operator
Blocks and scopes are often used in the programming languages. we also know that the same variable names can be used to have different meaning in different blocks. the scope of the variable is from the point of the deceleration to the end of the block containing the deceleration, a variable declared in a block is said as local to that block. For example.
... { x = 10; ... ... } ... ... { int x = 20; ... ... }
In the above two blocks the x declared are two different variables at different memory location, we can not access the the variable outside the block or the other variable in side the different block.
The Scope resolution operator is used for many other purpose, which are listed below:
- For accessing the global variable when there is a local variable with the same name.
- Defining the function outside the class.
- Accessing a class’s static variables.
- Referring to a class inside another class.
- In case of multiple Inheritance.
- Namespace
Accessing the Global variable when the local variable with same name.
#include<iostream> using namespace std; int x = 30; int main(){ int x = 10; cout << "Value of global x is " << ::x<<endl; cout << "Value of local x is " << x; return 0; }
output:
Value of global x is 30 Value of local x is 10
Defining the function outside the class.
#include <iostream> using namespace std; class jk{ public: void study(); }; void jk::study(){ cout << "study of Class jk Called….. :)"; } int main(){ jk c; c.study(); return 0; }
Accessing a class’s static variables.
#include<iostream> using namespace std; class Try{ static int x; public: static int y; void function(int x){ cout << "Static x : " << Try::x <<endl; cout << "Local x : " << x; } }; int Try::x = 10; int Try::y = 15; int main(){ Try t; int x = 20 ; t.function(x); cout <<endl<< "Try::y = " << Try::y; return 0; }
Referring to a class inside another class.
#include<iostream> using namespace std; class Outside_class{ public: int jk; class Inside_class{ public: int jk; static int x; }; }; int Outside_class::Inside_class::x = 5; int main(){ Outside_class A; Outside_class::Inside_class B; return 0; }
In case of multiple Inheritance.
#include<iostream> using namespace std; class jk1 { protected: int n; public: jk1() { n = 10; } }; class jk2{ protected: int n; public: jk2() { n = 20; } }; class Child: public jk1, public jk2{ public: void function() { cout << "jk1's n is " << jk1::n<<endl; cout << "jkt2's n is " << jk2::n; } }; int main() { Child o; o.function(); }
Namesapce.
Suppose we have two namespaces & both contains class with same name. So to avoid any conflict we can use namespace name with the scope resolution operator. In the below example we are using std::cout.
#include<iostream>
int main(){
std::cout << "Hello Crews" << std::endl;
}
Comments
Post a Comment
if you have any doubts, let me know