Search code examples
c++reference

Understanding "return *this" and class reference


I'm currently learning about object-oriented programming in C++, and I'm trying to wrap my head around the concepts of the this pointer, the return *this statement, and the use of references.

I've come across an example code snippet that demonstrates these concepts, but I'm still struggling to fully understand how they work together.

Here's the example code:

#include <iostream>

using namespace std;

class MyClass {
public:
    MyClass& setNum(int num) {

        this->num = num;
        return *this;  
    }

    MyClass& displayNum() {
        cout << "Num: " << this->num << endl;
        return *this;  
    }
private:
    int num;
};

int main() {
    MyClass obj;
    obj.setNum(10).displayNum();  
    return 0;

}

What does it mean that the this pointer is returned in this example?


Solution

    1. What is the purpose of the this pointer in this context? How does it work?

    In this->num = num;, this is used to tell the compiler that it's the num member variable that should be assigned to. With only num = num; you would assign the function parameter num to itself (a no-op). This is because the local num (declared as a function parameter) shadows the member variable num. It's usually best to not have shadowing. Had the function parameter and the member variable had different names, this-> could have been removed.

    In displayNum, this-> could be removed. There is no shadowing so num refers to the member variable num. Returning *this "dereferences" this so that you can return a reference to the current MyClass instance. If the function had been declared to return MyClass instead of MyClass&, return *this; would have returned a copy of the MyClass instance.

    1. Can someone explain the meaning of return *this; in the setNum and displayNum methods? Why do we return a reference to the current instance?

    It allows for "chaining" operations. Example:

    obj.setNum(10).displayNum();
    

    Since setNum() returns a reference to obj, displayNum() will be called on obj too.

    1. Why do we use references (MyClass&) as the return type for these methods? What are the advantages of returning a reference rather than a value or a pointer?

    It depends what you want to do. In some "setter" methods, people prefer to return nothing - or return the previous value. In the application you got MyClass from, they seem to have wanted chaining.

    Chaining is what makes things like this work:

    if ( (a = func()) == b ) { ... }
    

    In the above, operator= returns a reference to a. This can then be used to compare with b. Had the assignment operator been void one would need to split the above into ...

    a = func();
    if (a == b) { ... }