zhirzh
zhirzh

Reputation: 3449

How does return by reference work in C++ classes?

In C++, if i type:

int x=5;
int &y=x;

then y will act as an alias for the memory location where original x is stored and this can be proven/tested by printing the memory location of both, x and y

the output of a similar program is below:

x is at location: 0x23fe14
y is at location: 0x23fe14

But what about classes?

when a member function is declared with return type as a reference and the function uses the this pointer, what is the function actually returning?

for example:

#include <iostream>
class simple
{
    int data;
public:
    // ctor
    simple():
        data(0)
        {}

    // getter function
    int& getter_data()
    {   return this->data;    }

    // modifier functions
    simple& add(int x=5)
    {   this->data += x;
        return *this;
    }
    simple& sub(int x=5)
    {   this->data -= x;
        return *this;
    }
};

int main()
{   simple obj;
    obj.add().sub(4);  ////////// how & why is it working? /////////
    std::cout<<obj.getter_data();
    getchar();
}

why is it possible to execute the command in highlighted line?

what kind of data is obj.add() returning to the sub()?

Upvotes: 0

Views: 189

Answers (2)

Frunsi
Frunsi

Reputation: 7147

what kind of data is obj.add() returning to the sub()?

obj.add() is returning a reference to the obj instance.

The text "returning to the sub()" is not making sense at all.

However, in your case, the reference to your object is very similar to a plain pointer to your object, and often it is a good metapher.

Upvotes: 0

Filip Ros&#233;en
Filip Ros&#233;en

Reputation: 63797

When your member-function returns simple& initialized with *this (*this being an instance of simple) the semantics are the same as your own "reference example"; a reference is initialized with an instance of that type.

You are initializing the returned reference with the object itself.


The below snippets are semantically equivalent:

obj.add ().sub (4);

simple& ref = obj.add ();

ref.sub (4); // `ref` is really `obj`,
             // the address of `ref` and `obj` are the same

Upvotes: 3

Related Questions