Scope resolution operator is for accessing static or class members and this pointer is for accessing object members when there is a local variable with the same name.
Consider below C++ program:
CPP
#include <iostream>
using namespace std;
class Test {
int a;
public :
Test() { a = 1; }
void func( int a) { cout << a; }
};
int main()
{
Test obj;
int k = 3;
obj.func(k);
return 0;
}
|
Explanation: The output for the above program is 3 since the “a” passed as an argument to the func shadows the “a” of the class .i.e 1
Then how to output the class’s ‘a’. This is where this pointer comes in handy. A statement like cout <<this->a instead of cout << a can simply output the value 1 as this pointer points to the object from where func is called.
CPP
#include <iostream>
using namespace std;
class Test {
int a;
public :
Test() { a = 1; }
void func( int a) { cout << this ->a; }
};
int main()
{
Test obj;
int k = 3;
obj.func(k);
return 0;
}
|
How about Scope Resolution Operator?
We cannot use the scope resolution operator in the above example to print the object’s member ‘a’ because the scope resolution operator can only be used for a static data member (or class members). If we use the scope resolution operator in the above program we get compiler error and if we use this pointer in the below program, then also we get a compiler error.
CPP
#include <iostream>
using namespace std;
class Test {
static int a;
public :
void func( int a) { cout << Test::a; }
};
int Test::a = 1;
int main()
{
Test obj;
int k = 3;
obj.func(k);
return 0;
}
|
If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
28 Nov, 2021
Like Article
Save Article