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;
}
}
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;
}
}
One of the main advantages of return by reference in classes is the ability to easily chain functions.
Suppose that your member function is to multiply a particular member of your class. If you make the header and source files to keep the information of the class and the definition of the member function separately, then, the header file
myclass.h
would be:and the source file:
myclass.cpp
would be:If you initialize an object called
obj
, the default constructor above setsmember1_
equal to 1: Then in your main function, you can do chains such as:Then
member1_
would now be 8. Of course, the idea might be to chain different functions, and alter different members.In the case you are using the return by pointer, the first call uses the object, and any subsequent call will treat the previous result as a pointer, thus
Because the return type is
void
, i.e.: you declare that you don't return anything. Change it tomyclass*
to returnthis
change tomyclass &
to return reference to the class through*this
.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.
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.