ipkiss
ipkiss

Reputation: 13661

How to know if the code in the overloaded assignment operator executes?

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?

Upvotes: 2

Views: 70

Answers (2)

Christoph
Christoph

Reputation: 2004

Regarding question 2: You return *this in order to enable chained assignments like s1 = s2 = s3 = ...

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258618

You're initializing s1, not assigning to it.

Sales_item s1 = s;

calls the compiler-generated copy constructor. It is equivalent to:

Sales_item s1(s);

You need:

Sales_item s1;
s1 = s;

Why Line 2 returns *this? - That's the idiomatic way of implementing the assignment operator, and I suggest you stick to it. It facilitates method and operation chaining.

Upvotes: 5

Related Questions