Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object reference vs Void return type for a Method

Tags:

c++

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?

like image 516
Xplane Avatar asked Jul 14 '13 23:07

Xplane


People also ask

Which is generally more efficient a function that returns an object by reference or a function that returns an object by value?

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.

Which is the correct return type for the process function method?

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 .

Are objects returned by reference?

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.


Video Answer


1 Answers

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:

  • What does object.method1().method2() mean?
  • What is the “Named Parameter Idiom”?
  • What's a fluent interface?
  • Fluent interface
like image 65
AliciaBytes Avatar answered Oct 18 '22 14:10

AliciaBytes