I have the following code:
class Sales_item {
public:
int ii;
Sales_item& operator=(const Sales_item &item)
{
cout << "Inside assignment\n"; // Line 1
ii = item.ii;
return *this; // Line 2
}
};
Then, I did:
(just an example)
Sales_item s;
Sales_item s1 = s;
But the Line 1 did not execute. How can I “see” code inside the overloaded assignment to get executed? For example, there might be complicated code and I want to debug? I have tried to set a breakpoint at Line 1, but the program did not jump into that breakpoint.
Why Line 2 returns *this? I have tried to change to void and got the same results. What’s the difference?
You’re initializing
s1, not assigning to it.calls the compiler-generated copy constructor. It is equivalent to:
You need:
Why
Line 2returns*this? – That’s the idiomatic way of implementing the assignment operator, and I suggest you stick to it. It facilitates method and operation chaining.