In Java you can simply return this to get the current object. How do you do this in C++?
Java:
class MyClass {
MyClass example() {
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:
#ifndef myclass_h
#define myclass_h
class myclass{
public:
int member1_;
double member2_;
myclass (){
member1_ = 1;
member2_ = 2.0;
}
myclass& MULT(int scalar);
myclass* MULTP(double scalar);
};
#endif
and the source file: myclass.cpp would be:
myclass& myclass::MULT(int scalar){
member1_ *= scalar;
return *this;
}
myclass* myclass::MULTP(double scalar){
member2_ *= scalar;
return this;
}
If you initialize an object called obj, the default constructor above sets member1_ equal to 1:
Then in your main function, you can do chains such as:
myclass obj;
obj.MULT(2).MULT(4);
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
obj.MULTP(2.0)->MULTP(3.0);