Normal overriding would work this way:
class Fruit {
public:
string color();
};
string Fruit::color() {
return "Unkown";
};
class Apple : public Fruit {
public:
string color();
};
string Apple::color() {
return "Green";
};
Now, you’ld call this like:
Apple *apple = new Apple();
std::cout << apple->color();
This will output Green, which is correct! However, running it in the following situation (which is just an example, of course):
Apple *apple = new Apple();
printHealthy(apple);
// Method printHealthy:
void printHealthy(Fruit *fruit) {
std::cout << fruit->color();
};
This will output Unkown, which I can understand, since you’re casting Apple to Fruit, and thus ‘replace’ its methods. But how can I still get to know its real color?
Requirements:
- I need to know what its real color is.
- I cannot rely on the
Apple-class. There will be lots of moreApple‘s, which are assigned on the go. - every
Apple-class (eg.Tomato, they have different names of course) is a subclass ofFruit. - not every class implements all methods. For example, there might be an
Applewhich color is ‘unkown’, so it doesn’t override that method and instead, runFruit‘s method.
Mark the function
virtualin the base class.