Given this class:
class Baz
{
public:
Baz() : Baz(0) {}
Baz(int i) { _i = i; }
Baz(Baz const &b) { _i = b._i * 10; }
~Baz() { }
private:
int _i;
};
If I debug and step through this code:
Baz a = 4;
The Baz constructor that takes an int is called, as expected, and I get a Baz with _i of 4. That's good.
But if I do this:
Baz b;
b = 4;
The first line calls the default constructor, as expected. The second line calls the int constructor and then the destructor.
My first expectation was that the second line of the second example would simply call the int constructor in assigning to b. I didn't expect the destructor to be called, but if it's first converting the integer 4 to a Baz before assignment, it would make sense to destroy it afterward. But then I'd expect the copy constructor to be called when assigning that temporary value to b. The Baz that is destroyed has the value 4 for _i, so it's not the object created on the first line.
What's going on here exactly? Why the difference between these two scenarios?