#include <iostream>
using namespace std;
class A
{
int x;
public:
A(int a)
{
x = a;
cout << "CTOR CALLED";
}
A(A &t)
{
cout << "COPY CTOR CALLED";
}
void display()
{
cout << "Random stuff";
}
A operator = (A &d)
{
d.x = x;
cout << "Assignment operator called";
return *this;
}
};
int main()
{
A a(3), b(4);
a = b;
return 0;
}
The output of this code is :
CTOR CALLED
CTOR CALLED
Assignment operator called
COPY CTOR CALLED
When I used the watch in visual studio it showed that the value of x in a had been changed even before the overloaded assignment operator was called.
So why is the copy constructor even being called here?
Because you return by value from the assignment operator. It should return a reference:
A& operator = (A &d) { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With