First of all, look at this syntax:
fruit func() override { return Orange(); }
What is override ? There is no such keyword in C ++ 03. This is only in C ++ 11. Therefore, make sure you use a compiler that knows about this keyword.
Secondly, in the derived class fruit really Orange . Overriding typedef is not a problem. The problem is that Orange and Apple are not covariant. Deriving one from the other will make them covariant. In your case, you must get Orange from Apple to make it work.
Note that you must change the return type from fruit to fruit* or fruit& .
class Orange : public Apple {};
The idea is that in the base class, the return type should be a pointer / reference of the base type (which is equal to Apple ), and in the derived class, the return type can be a pointer / reference of the type Apple or any class that derives from it.
By the way, does that make sense? Withdraw
Orange from
Apple ?
What about the next design class?
class Fruit {}; class Apple : public Fruit {}; class Orange : public Fruit {}; class Base { virtual Fruit* f(); }; class Derived : public Base { virtual Fruit* f(); };
No need to use typedef .
source share