2

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?

Eric
  • 95,302
  • 53
  • 242
  • 374
  • 2
    The answer to your question is [here](http://stackoverflow.com/questions/12009865/operator-and-functions-that-are-not-inherited-in-c) – Andy Prowl Mar 01 '13 at 13:36

2 Answers2

9

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=;
};
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • What if class `Y` needs to "extend" the operator `=`, i.e. do more things than `return *this` in parent class? – Ignorant Dec 07 '15 at 17:35
  • Then you override it yourself as you did initially and don't use inheritance. I have personally found that using virtual operator overloads are not always the best thing – Curious Jan 01 '16 at 00:00
0

You are forgetting the methods that the compiler automatically generates if they are not declared. Assignment is amongst them.

Ed Heal
  • 59,252
  • 17
  • 87
  • 127