How do c++ functions return this -
i saw example in answer here on stackoverflow regarding returning in c++ function return “this” in c++?, question how handle returns of handled in c++. best answer said
class myclass { public: // return pointer needs const , non-const versions myclass* returnpointertocurrentobject() { return this; } const myclass* returnpointertocurrentobject() const { return this; } // return reference needs const , non-const versions myclass& returnreferencetocurrentobject() { return *this; } const myclass& returnreferencetocurrentobject() const { return *this; } // return value needs 1 version. myclass returncopyofcurrentobject() const { return *this; } };
now dont understand how
myclass& returnreferencetocurrentobject() { return *this; }
cannot same as
myclass returncopyofcurrentobject() const { return *this; }
as see first example returns reference , second returns dereferenced pointer (value)? how can these 2 functions have same function body?
as see first example returns reference , second returns dereferenced pointer (value)?
exactly. first returns reference object it's called on; second returns copy of object.
how can these 2 functions have same function body?
because conversion return expression *this
return value implicit. in first case, it's converted reference; in second, it's converted value copying it.
Comments
Post a Comment