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'
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.
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.
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.
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.
this
is a pointer. So it should be return *this;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With