C++ | this pointer | Question 3

Predict the output of following C++ program.

filter_none

edit
close

play_arrow

link
brightness_4
code

#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


(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



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.