Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does an overloaded assignment operator not get inherited? [duplicate]

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?

like image 220
Eric Avatar asked Nov 29 '25 16:11

Eric


1 Answers

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=;
};
like image 155
Mike Seymour Avatar answered Dec 02 '25 07:12

Mike Seymour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!