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()?
When your member-function returns
simple&initialized with*this(*thisbeing an instance ofsimple) 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: