Home > Back-end >  c return *this, how to think it
c return *this, how to think it

Time:03-01

When I searched for return *this, I found someone explaining it as a chained assignment function. enter image description here

But when I follow the blogger's implementation, I found that this is not the case. return *this //return *this

Though one has the code return *this, the other has not, the two results is same.

#include <iostream>
using namespace std;
class Wd {
private:
public:
    int a;
    int b;
    Wd &operator=(Wd const &as) {
        this->a = as.a;
        this->b = as.b;
        return *this;
    };
};

int main() {
    Wd a;
    a.b =3;
    a.a =4;
    Wd c,b,d;
    d.a=6;
    d=c=b=a;
    cout<<d.a<<a.a<<b.a<<c.a<<endl;
    return 0;
}

CodePudding user response:

Semantic of assignment expression like a=b is :

  • first, set the value of a to the value of b,
  • second, the value of the whole expression is the value of a after assignment. a=b=c is equivalent to a = (b=c).

As a=b is a.operator=(b), the return value of the operator must be the value of a after assignment, thus the following is the most common way of implementing it:

K &operator=(const K &arg) {
    // code to assign this with values in arg
    return *this; // return the current assigned object
}

CodePudding user response:

So this

class Wd{
public:
    int a;
    int b;
    Wd &operator =(Wd const &as){
        this->a = as.a;
        this->b = as.b;
        return *this;
    };
};

creates an object with only one function operator=.

That function is defined as returning a reference to the invoking object.

    return *this;

says 'return what the this object points at'. this points at the current Wd instance. If the retrun type we Wd then it would retunr a copy, but becuase the return type is Wd& it returns a reference to it, this is effectively a pointer

so now look at the main code

        Wd a;
        a.b =3;
        a.a =4;

first we create a Wd and initialize its members.

Then we do (simplified a bit)

        Wd c;
        Wd d;
        d = c = a;

d = c= a translates to

       d.operator=(c.operator=(a))

and because c.operator=(a) returns a reference to a this is equivalent to

      d.operator=(a)

One of the main reason for the existance of references is to permit chaining like this. The most well known one is this

     cout << x << " " << y << "!!" << z;

this works because operator<< for streams is defined as returning a reference to its invoking stream.

  •  Tags:  
  • c
  • Related