1

why I am not able to modify this pointer? getting compilation error "error: lvalue required as left operand of assignment". Following is the 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;
}
pankaj kushwaha
  • 369
  • 5
  • 20

1 Answers1

4

You can't assign to this, you should think of it as conceptually constant pointer Test *const this.

What you actually need to do in change() is just copy the contents of t:

void change(Test *t) {this->x = t->x;}

If you want to be a good C++ citizen you could also make t constant:

void change(const Test *t) {this->x = t->x;}
Sean
  • 60,939
  • 11
  • 97
  • 136