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?
This line
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
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.