Introduction
To understand the scope resolution operator vs this pointer, we will first separately discuss the scope resolution operator in C++ and how to use it. We will discuss this pointer in C++ and its uses. And at last, we will discuss the scope resolution operator vs this pointer.
Also, see Literals in C, Fibonacci Series in C++
Scope Resolution Operator in C++
Scope resolution operator in C++ is written as two colon symbols(::). It is used to access static or class members of a class in C++.
If we have a function that has a local variable name, same as the name of a static member, and we access the variable by name, then the local variable has the precedence, and it shadows the static variable. The value of the local variable is printed. So, to access the static variable, we have to use the scope resolution operator(::) with the class name in the given syntax.
class_name :: static_variable_name
Following is an example of how we can use the scope resolution operator in C++ to access the static members or class members.
#include<iostream>
using namespace std;
class Demo{
//class member var
static int var;
public:
//A function that prints the value of var
void demo_func(int var){
cout<<Demo::var<<endl; //By using :: we can access the static variable
cout<<var; //This will print the local variable
}
};
//It is necessary to explicitly define static member in C++
int Demo::var = 75;
//Driver function
int main(){
Demo obj;
obj.demo_func(10);
return 0;
}
Output
75
10
You can try and compile with the help of online c++ compiler.