Why does this 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 the error:
prog.cpp: In function ‘int main()’:
prog.cpp:14:9: error: no match for ‘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 for argument 1 from ‘int’ to ‘const Y&’
prog.cpp:8:7: note: Y& Y::operator=(Y&&)
prog.cpp:8:7: note: no known conversion for argument 1 from ‘int’ to ‘Y&&’
Why is the + operator inherited, but the = operator not?
Class Y contains implicitly-declared assignment operators, which hide the operator declared in the base class. In general, declaring a function in a derived class hides any function with the same name declared in a base class.
If you want to make both available in Y, use a using-declaration:
class Y : public X {
public:
using X::operator=;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With