ZELIBOBA
ZELIBOBA

Reputation: 133

How works returning an object by reference

As i understand it is my reference SomeClass &ref=b; After that b = ref; Then c = b; SomeClass &ref2=c; then c=ref2 . But am I calling the operator = witch i have reloaded when b=ref or c = ref2 ? Something like that a.operator=(ref) ?

class SomeClass
{
public:
    SomeClass()
    {
        a = 5;
    }
    SomeClass(int l_a)
    {
        a = l_a;
    }

    SomeClass& operator=(const SomeClass& l_copy)
    {
        this->a = l_copy.a;
        return *this;
    }

    int a;
};

int main()
{
    SomeClass a;
    SomeClass b(1);
    SomeClass с(6);
    с = b = a;

}

Upvotes: 1

Views: 59

Answers (2)

André Caceres
André Caceres

Reputation: 729

If you had:

void operator=(const SomeClass& l_copy)
    {
        this->a = l_copy.a;
    }

Then your assignments operations would be limited to:

b = a;
c = b;

By returning the reference you can chain assignments as in:

c = b = a;
// c.operator = (b.operator = (a));

//1: b.operator= ("ref a")
//2: c.operator= ("ref b")

Upvotes: 1

Zàkelis
Zàkelis

Reputation: 39

By overloading the operator = in SomeClass, you are doing copy-assignment lhs = rhs (Eg : c = b, c is lhs and b is rhs). Because it returns a reference matching SomeClass& operator= expected parameter type, you can chain multiple copy-assignments such as c = b = a.

Upvotes: 1

Related Questions