I'm trying to write an abstract class with some pure virtual binary operators, which should be implemented by the derived class in order to accomplish operator polymorphism. Here's a simplified example:
class Base {
public:
virtual const Base& operator+ (const Base&) const = 0;
};
class Derived : public Base {
public:
const Derived& operator+ (const Derived&) const;
};
const Derived& Derived::operator+ (const Derived& rvalue) const {
return Derived();
}
It doesn't matter right now what the operator does, the important part is what it returns: it returns a temporary Derived object, or a reference to it. Now, if I try to compile, I get this:
test.cpp: In member function ‘virtual const Derived& Derived::operator+(const Derived&) const’:
test.cpp:12:17: error: cannot allocate an object of abstract type ‘Derived’
test.cpp:6:7: note: because the following virtual functions are pure within ‘Derived’:
test.cpp:3:22: note: virtual const Base& Base::operator+(const Base&) const
What's wrong? Isn't operator+ (the only pure virtual function in Base) being overriden? Why should Derived be abstract as well?
const Derived& Derived::operator+ (const Derived& rvalue) const
vsvirtual const Base& Derived::operator+ (const Base&) const
– Pledgeeoperator+
needs to return by value, which rules out returning aDerived
when your caller expects aBase
. – Schweitzer