Adhvaitha
Adhvaitha

Reputation: 274

Question on using this pointer

I tried copying a pointer to another by using a method inside the class and the this pointer as follows. I am giving the entire test code so that it is clear what is going on.

class test  {
private:
    int x;
public:
    void setx(int x);
    int getx(void);
    void copy(test *temp);
};

void test::setx(int x)  {
    this->x = x;
}

int test::getx(void)    {
    return this->x;
}

void test::copy(test *temp) {
    this = temp;
}

And I access this method from the main as follows:

int main()  {
    test a;
    a.setx(4);
    cout << a.getx()<<endl;
    test *b = new test;
    b->setx(4);
    cout << b->getx()<<endl;
    test *c;
    c=b;
    cout << c->getx()<<endl;
    test *d;
    d->copy(b);
    cout << d->getx()<<endl;
}

However it gives the following error

In member function ‘void test::copy(test*)’:
error: lvalue required as left operand of assignment

All the other method involving the this pointer works fine except for the copying part. Am i doing some elementary mistake in using the this pointer?

Upvotes: 1

Views: 748

Answers (3)

Henrik
Henrik

Reputation: 23324

You cannot modify the this pointer. You can however modify *this:

void test::copy(test *temp)
{
    *this = *temp;
}

Also, you should rename the data member or the parameter, so you don't need this->:

class test
{
int m_x;
public:
void setx(int x)
{
    m_x = x;
}

Upvotes: 2

pokey909
pokey909

Reputation: 1837

what is test::copy supposed to do? Clearly you cant assign a different address to your current object. So it is invalid.

if this is supposed to initialize the current object with the values of some other object then it should look like this:

void test::copy(test *temp) {
    this->x = temp->getX();
}

Upvotes: 1

Nicol Bolas
Nicol Bolas

Reputation: 473212

You cannot overwrite this. The this pointer is a constant, so you're not allowed to change it. And what would that mean anyway? You can't change the object that you're in. You can change the values within that object, but not the object itself.

You need to copy other objects by value (by what is stored in the object), not by pointer.

Also, you shouldn't have a function called copy; that's what copy constructors and copy assignment operators are for.

Upvotes: 7

Related Questions