Skip to content
Related Articles

Related Articles

C++ | this pointer | Question 3
  • Difficulty Level : Hard
  • Last Updated : 31 Jul, 2013

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;
}

(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

Want to learn from the best curated videos and practice problems, check out the C Foundation Course for Basic to Advanced C.
My Personal Notes arrow_drop_up
Recommended Articles
Page :