Consider below C++ program:
The output for the above program is 3 since the “a” passed as 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 <a” instead of “cout << a" can simply output the value 1 as this pointer points to the object from whom func is called.
How about Scope Resolution Operator? We cannot use Scope resolution operator in above example to print object’s member ‘a’ because scope resolution operator can only be used for a static data member (or class members). If we use scope resolution operator in above program we get compiler error and if we use this pointer in below program, then also we get compiler error.
Conclusion is 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 same name.
This article is contributed by Aakash Sachdeva. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to firstname.lastname@example.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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Scope resolution operator in C++
- Double Pointer (Pointer to Pointer) in C
- For Versus While
- typedef versus #define in C
- Pointer to an Array | Array Pointer
- What is a Pointer to a Null pointer
- C | Variable Declaration and Scope | Question 1
- C | Variable Declaration and Scope | Question 2
- C | Variable Declaration and Scope | Question 3
- C | Variable Declaration and Scope | Question 4
- C | Variable Declaration and Scope | Question 6
- C | Variable Declaration and Scope | Question 7
- C | Variable Declaration and Scope | Question 8
- Scope of Variables in C++
- Scope rules in C
- vector::operator= and vector::operator[ ] in C++ STL
- deque::operator= and deque::operator in C++ STL
- Why overriding both the global new operator and the class-specific operator is not ambiguous?
- Operator Overloading '<<' and '>>' operator in a linked list class
- How to declare a pointer to a function?
Improved By : Prateek Tamrakar