I was looking at some open source source code and I noticed that for some methods, rather than using void for a return type, they had used a reference to that class.
Example:
class Object
{
private:
float m_x;
public:
Object();
Object& setX(float x)
{
m_x = x;
return *this;
}
};
Normally, I would write the same function like this:
class Object
{
private:
float m_x;
public:
Object();
void setX(float x)
{
m_x = x;
}
};
Is there any advantage of using one over the other?
Returning the object should be used in most cases because of an optimsation called copy elision. However, depending on how your function is intended to be used, it may be better to pass the object by reference.
As a good engineering practice, always specify a return type for your functions. If a return value isn't required, declare the function to have void return type. If a return type isn't specified, the C compiler assumes a default return type of int .
User-defined functions and class methods can define return types as object references (as class or interface types). When an object is passed locally, class instances are always returned by reference. Thus, only a reference to an object is returned, not the object itself.
Yes, there are some advantages with returning a reference. When returning a reference you can keep on working on the returned reference and chain multiple function calls together. For example if there were a setY
function too, you could do this:
object.setX(5).setY(10);
Returning a reference doesn't really have disadvantages but allows some nice things. It can be used to create fluent interfaces, workaround the lack of named parameters in C++ if you want, and other things.
Related reads:
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