Reputation: 2039
I have a MyPoly class where I implemented my own equal operator ( = ). When I try this code everything works fine and my implemented = is being called.
MyPoly mp = MyPoly(arr , 4);
MyPoly copy;
copy = mp;
But when I write this:
MyPoly mp = MyPoly(arr , 4);
MyPoly copy = mp;
It doesn't use my implemented = , and then when the destructor is called I get a run time error.
Can someone explain why these codes are different?
Upvotes: 1
Views: 156
Reputation: 227418
This line
MyPoly copy = mp;
is a copy initialization, so it does not call the assignment operator (what you refer to as "equal operator"), but rather the copy constructor, which has signature
MyPoly(const MyPoly&);
and is generated by the compiler unless you provide your own. As to the runtime error, you need to provide more code. But I could speculate that, since you have written your own assignment operator, you may be dealing with some dynamically allocated resources, in which case you should follow the rule of three and implement your own copy constructor and destructor. And if you have C++11 support, you should extend that into the rule of 5 and provide your own move copy constructor and move assignment operator.
Upvotes: 8
Reputation: 258618
This
MyPoly copy = mp;
is not assignment, but copy initialization. It uses the copy constructor, not the assignment operator.
MyPoly copy(mp);
is direct initialization.
MyPoly copy;
copy = mp;
is assignment.
Upvotes: 4
Reputation: 55887
MyPoly mp = MyPoly(arr , 4);
MyPoly copy = mp;
Calls copy c-tor
, not operator =
. It's copy initialization
in both cases.
Upvotes: 3
Reputation: 90
MyPoly copy = mp;
Is the same as:
MPoly copy(mp);
As in, it invokes the copy constructor instead of the assignment operator. Creating a copy constructor alongside an assignment operator is always a good idea.
Upvotes: -1