Search code examples
c++classreturn-by-reference

Returning objects by reference


#include<iostream>
using namespace std;
class my_class
{
    int m,n;
public:
    void show(void);
    my_class& test(my_class b)
    {
        static my_class c;
        c.m=m+b.m;
        c.n=n+b.n;
        return c;
    }
    my_class(int x,int y) //Parametrized constructor
    {
        m=x;n=y;
    }
    my_class(){} //Default consructor
};
void my_class::show(void)
{
    cout<<m<<" "<<n;
}
main()
{
    my_class a(2,3),b(3,4); //Object initialisation
    my_class d=a.test(b);
    d.show();
}

The function test returns a reference to a static object c defined in the function.I get the output as 5 7.I need help regarding the following:

  • I can also achieve the same output by returning my_class instead of my_class&.How does return by value compare with return by reference here?Are data members of the returned reference copied in the assignment statement my_class d=a.test(b) to object d? Or is d just an alias for the returned reference?
  • If I change the assignment statement to my_class& d=a.test(b), even then I get the same output.Does this mean that both ways of writing the above statement are right?

  • Can you please explain what exactly is happening in both the kinds of assignment statements?


Solution

  • How does return by value compare with return by reference here?Are data members of the returned reference copied in the assignment statement my_class d=a.test(b) to object d?

    Yes, d is copy-initialized using the referenced object. (Although, that's indeed not an assignment, nor a statement).

    ...Or is d just an alias for the returned reference?

    No, d is not a reference, and not an alias of a reference. It is a non-reference variable.

    If I changed the assignment statement to my_class& d=a.test(b), even then I get the same output?Does this mean that both ways of writing the above statement are right?

    Depends on the definition of right. Neither of the options are ill-formed, but they do different things. What is right depends on what you intend to do.

    Can you please explain what exactly is happening in both the kinds of assignment statements?

    • When you return a value, a temporary object is created that is copy-initialized from the return expression.
    • When you return a reference, no temporary copy is created.
    • When you copy-initialize from a returned temporary, yet another temporary is created, and the reference argument of the implicit copy constructor is bound to it.
    • When you copy-initialize from a returned reference, the reference argument of the implicit copy constructor is bound to object referenced by the returned reference.
    • When you bind a reference to the returned reference, it is bound to the referenced object.

    The standard allows some of the mentioned copies to be elided.