Take the 2-minute tour ×

When I return the pointer to the reference type in a function, I got a compiler error initial value of reference to non-const must be an lvalue. The function is like this

Testing& copy(Testing test)
    x = test.x;
    return this;

But when I change the this to *this, the error is gone.

Thanks in advanced.

share|improve this question
References can't have pointers, but pointers can have references. If you want to return a pointer to your object, return this. If you want to return a reference to your object, return *this. –  WhozCraig Jan 9 '13 at 12:17
What is your question ? this is pointer, *this is a reference, and your function compile if you return a reference. There's no question. –  Stephane Rolland Jan 9 '13 at 12:18
@WhozCraig could you elaborate, I absoluletly do not see what you try to mean. –  Stephane Rolland Jan 9 '13 at 12:20
@StephaneRolland I mean you can have reference to a pointer (such as an out-param pointer passed by reference (int *& int_ptr_ref), but you cannot have a pointer to a reference (this is not allowed: int&* var;). A pointer to a reference would be nothing more than a pointer to the referenced object, which is nothing more than taking the address of the object (through a reference or otherwise) Such as as int a; int& b=a, int* c = &b; the address in c is &a; –  WhozCraig Jan 9 '13 at 12:23
@WhozCraig Okay. Not sure it was directly helping the OP though :-) –  Stephane Rolland Jan 9 '13 at 12:28
show 2 more comments

closed as not a real question by Stephane Rolland, WhozCraig, BЈовић, Linger, rds Jan 9 '13 at 14:33


2 Answers

In C++, the this special variable holds a pointer to the class instance.

You're creating a function that returns a reference to an instance, another name to the same memory position.

When you use *this you're dereferencing the this pointer, getting to the real memory position holding the current instance and returning an alias to that.

It does work! Just beware of the Object Slicing Problem in case you need Polymorphism.

share|improve this answer
Slicing only applies when returning/assigning by value. –  Angew Jan 9 '13 at 12:59
add comment

Pointers and references are not the same thing. this is a pointer to the current class instance, while *this is the actual instance as a value (to be more specific, an lvalue, when used as a return value).

share|improve this answer
add comment
