开发者

C++ dynamic type - overriding methods

开发者 https://www.devze.com 2023-03-12 16:29 出处:网络
Normal overriding would work this way: class Fruit { public: string color(); }; string Fruit::color() { return \"Unkown\";

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开发者_StackOverflow社区();

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 more Apple's, which are assigned on the go.
  • every Apple-class (eg. Tomato, they have different names of course) is a subclass of Fruit.
  • not every class implements all methods. For example, there might be an Apple which color is 'unkown', so it doesn't override that method and instead, run Fruit's method.


Mark the function virtual in the base class.

class Fruit {
public:
    virtual string color();
};


You forgot virtual. Add the virtual keyword to the declaration of color and your code will print the correct colour. C++ will only perform a dynamic lookup on functions declared as virtual.


The color method should be a virtual method.

Right now, the color method is not virtual. The compiler decides at compile time which method to call. What you want is to do this at runtime, based on the actual type of the class.

0

精彩评论

暂无评论...
验证码 换一张
取 消