C++ | this pointer | Question 2
What is the use of this pointer?
(A) When local variable’s name is same as member’s name, we can access member using this pointer.
(B) To return reference to the calling object
(C) Can be used for chained function calls on an object
(D) All of the above
Answer: (D)
Explanation: See following example for first use.
/* local variable is same as a member's name */
class Test
{
private:
int x;
public:
void setX (int x)
{
// The 'this' pointer is used to retrieve the object's x
// hidden by the local variable 'x'
this->x = x;
}
void print() { cout << "x = " << x << endl; }
};
And following example for second and third point.
#include
using namespace std;
class Test
{
private:
int x;
int y;
public:
Test(int x = 0, int y = 0) { this->x = x; this->y = y; }
Test &setX(int a) { x = a; return *this; }
Test &setY(int b) { y = b; return *this; }
void print() { cout << "x = " << x << " y = " << y << endl; }
};
int main()
{
Test obj1(5, 5);
// Chained function calls. All calls modify the same object
// as the same object is returned by reference
obj1.setX(10).setY(20);
obj1.print();
return 0;
}
Recommended Posts:
- Double Pointer (Pointer to Pointer) in C
- C++ | this pointer | Question 3
- C++ | this pointer | Question 5
- C++ | this pointer | Question 1
- C++ | this pointer | Question 4
- C | Advanced Pointer | Question 3
- C | Advanced Pointer | Question 5
- C | Pointer Basics | Question 13
- C | Pointer Basics | Question 10
- C | Pointer Basics | Question 11
- C | Advanced Pointer | Question 4
- C | Pointer Basics | Question 15
- C | Pointer Basics | Question 12
- C | Advanced Pointer | Question 10
- C | Pointer Basics | Question 1



