Why doesn't a derived class use the base class operator= (assignment operator)?

本秂侑毒 提交于 2019-12-03 23:52:00

This is a subtle interaction between a compiler-generated operator= method and member function hiding. Since the Derived class did not declare any operator= members, one was implicitly generated by the compiler: Derived& operator=(const Derived& source). This operator= hid the operator= in the base class so it couldn't be used. The compiler was still able to complete the assignment by creating a temporary object using the Derived(int) constructor and copy it with the implicitly generated assignment operator.

Because the function doing the hiding was generated implicitly and wasn't part of the source, it was very hard to spot.

This could have been discovered by using the explicit keyword on the int constructor - the compiler would have issued an error instead of generating the temporary object automatically. In the original code the implicit conversion is a well-used feature, so explicit wasn't used.

The solution is fairly simple, the Derived class can explicitly pull in the definition from the Base class:

using Base::operator=;

http://ideone.com/6nWmx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!