Reputation: 2470
#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?
Upvotes: 2
Views: 121
Reputation: 36483
As @SomeProgrammerDude already said, it's because you return by value, not by reference like you usually do with an assignment operator. I would like to add that your assignment operator is currently the wrong way around:
A operator = (A &d)
{
d.x = x;
cout << "Assignment operator called";
return *this;
}
Usually you pass d
by const reference because we want to alter the members of this
. You are changing the members of d
. Which would functionally turn your a = b;
into b = a;
since a = b;
is actually changing members of b
now !
Making d
a const&
prevents these mistakes.
You should change it to:
A& operator = (A const &d)
{
x = d.x;
cout << "Assignment operator called";
return *this;
}
Upvotes: 3
Reputation: 409196
Because you return by value from the assignment operator. It should return a reference:
A& operator = (A &d) { ... }
Upvotes: 6