Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return reference from class to this

I have the following member of class foo.

foo &foo::bar()
{
   return this;
}

But I am getting compiler errors. What stupid thing am I doing wrong?

Compiler error (gcc): error: invalid initialization of non-const reference of type 'foo&' from a temporary of type 'foo* const'

like image 299
Thomas Avatar asked Apr 12 '10 11:04

Thomas


People also ask

What does it mean to return a reference?

It means you return by reference, which is, at least in this case, probably not desired. It basically means the returned value is an alias to whatever you returned from the function. Unless it's a persistent object it's illegal.

What does it mean to return a reference C++?

Returning values by reference in C++ A C++ function can return a reference in a similar way as it returns a pointer. When a function returns a reference, it returns an implicit pointer to its return value. This way, a function can be used on the left side of an assignment statement.

Can you return a class C++?

Passing and Returning Objects in C++ In C++ we can pass class's objects as arguments and also return them from a function the same way we pass and return other variables. No special keyword or header file is required to do so.

What happens if you return a reference?

Functions in C++ can return a reference as it's returns a pointer. When function returns a reference it means it returns a implicit pointer.


1 Answers

this is a pointer. So it should be return *this;

like image 193
Naveen Avatar answered Sep 29 '22 09:09

Naveen