Hi,

I have overloaded assignment operator like below and it worked perfectly fine.

void Test::operator = (Test& obj)
{
    this->a = obj.a;
    this->b = obj.b;
}

But when I googled more about this, I could see all of the examples used a different prototype like this

Test& Test::operator = (Test& obj)
{
    //do something on *this
    return *this;
}

Is there anything wrong in the first method?

Recommended Answers

All 3 Replies

Yes, I'm surprised your compiler allowed it. The assignment operator must return a reference to the object.

How, with the first method, would you expect to support something like a = b = c; ?

How, with the first method, would you expect to support something like a = b = c; ?

satisfying answer. thank you :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.