c++ - Why does an overloaded assignment operator not get inherited? -
this question has answer here:
- trouble inheritance of operator= in c++ 5 answers
- operator= , functions not inherited in c++? 3 answers
why code:
class x { public: x& operator=(int p) { return *this; } x& operator+(int p) { return *this; } }; class y : public x { }; int main() { x x; y y; x + 2; y + 3; x = 2; y = 3; } give error:
prog.cpp: in function ‘int main()’: prog.cpp:14:9: error: no match ‘operator=’ in ‘y = 3’ prog.cpp:14:9: note: candidates are: prog.cpp:8:7: note: y& y::operator=(const y&) prog.cpp:8:7: note: no known conversion argument 1 ‘int’ ‘const y&’ prog.cpp:8:7: note: y& y::operator=(y&&) prog.cpp:8:7: note: no known conversion argument 1 ‘int’ ‘y&&’ why + operator inherited, = operator not?
class y contains implicitly-declared assignment operators, hide operator declared in base class. in general, declaring function in derived class hides function same name declared in base class.
if want make both available in y, use using-declaration:
class y : public x { public: using x::operator=; };
Comments
Post a Comment