In Java you can simply return this
to get the current object. How do you do this in C++?
Java:
class MyClass { MyClass example() { return this; } }
this means pointer to the object, so *this is an object. So you are returning an object ie, *this returns a reference to the object.
Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void. Function Name − This is the actual name of the function.
A return statement ends the execution of a function, and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can return a value to the calling function.
The statement return this; returns the address of the object while the statement return *this; returns the value of the object.
Well, first off, you can't return anything from a void
-returning function.
There are three ways to return something which provides access to the current object: by pointer, by reference, and by value.
class myclass { public: // Return by pointer needs const and non-const versions myclass* ReturnPointerToCurrentObject() { return this; } const myclass* ReturnPointerToCurrentObject() const { return this; } // Return by reference needs const and non-const versions myclass& ReturnReferenceToCurrentObject() { return *this; } const myclass& ReturnReferenceToCurrentObject() const { return *this; } // Return by value only needs one version. myclass ReturnCopyOfCurrentObject() const { return *this; } };
As indicated, each of the three ways returns the current object in slightly different form. Which one you use depends upon which form you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With