C++ | this pointer | Question 3
Predict the output of following C++ program.
#include<iostream> using namespace std; class Test { private: int x; public: Test(int x = 0) { this->x = x; } void change(Test *t) { this = t; } void print() { cout << "x = " << x << endl; } }; int main() { Test obj(5); Test *ptr = new Test (10); obj.change(ptr); obj.print(); return 0; } |
chevron_right
filter_none
(A) x = 5
(B) x = 10
(C) Compiler Error
(D) Runtime Error
Answer: (C)
Explanation: this is a const pointer, so there is an error in line “this = t;”
Quiz of this Question
Recommended Posts:
- Double Pointer (Pointer to Pointer) in C
- C++ | this pointer | Question 1
- C++ | this pointer | Question 5
- C++ | this pointer | Question 2
- C++ | this pointer | Question 4
- C | Pointer Basics | Question 3
- C | Pointer Basics | Question 4
- C | Pointer Basics | Question 15
- C | Advanced Pointer | Question 8
- C | Pointer Basics | Question 2
- C | Pointer Basics | Question 17
- C | Advanced Pointer | Question 9
- C | Advanced Pointer | Question 3
- C | Pointer Basics | Question 1
- C | Pointer Basics | Question 17



