Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return "this" in C++?

Tags:

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;     } } 
like image 694
nobody Avatar asked Aug 02 '11 22:08

nobody


People also ask

What does * this return?

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.

What is return type in C?

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.

What is return value in C?

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.

What is the difference between the two statements return this and return * this?

The statement return this; returns the address of the object while the statement return *this; returns the value of the object.


1 Answers

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.

like image 79
Robᵩ Avatar answered Nov 03 '22 21:11

Robᵩ