class - How does return by reference work in C++ classes? -
in c++
, if type:
int x=5; int &y=x;
then y
act alias memory location original x
stored , can proven/tested printing memory location of both, x
, y
the output of similar program below:
x @ location: 0x23fe14 y @ location: 0x23fe14
but classes?
when member function declared return type reference , function uses this
pointer, function 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 working? ///////// std::cout<<obj.getter_data(); getchar(); }
why possible execute command in highlighted line?
what kind of data obj.add()
returning sub()
?
when member-function returns simple&
initialized *this
(*this
being instance of simple
) semantics same own "reference example"; reference initialized instance of type.
you initializing returned reference object itself.
the below snippets semantically equivalent:
obj.add ().sub (4);
simple& ref = obj.add (); ref.sub (4); // `ref` `obj`, // address of `ref` , `obj` same
Comments
Post a Comment