Search code examples
c++returnthis

return "this" in C++?


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;
    }
}

Solution

  • 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.