Search code examples
c++classc++11derived-classabstract-base-class

Array of pointers to base class: how to call unique derived class method


Been Googling for a while on this one, but can't seem to find a clear answer.

How do I call the unscramble() method in the following example?

Thanks. :^)

class Food {
public:
    Food(string _t):type(_t);
    virtual void eat() = 0;
private:
    string type;
}

class Fruit : public Food {
public:
    Fruit(string _t):Food(_t) {
    virtual void eat() { // Yummy.. }
}   

class Egg : public Food {
public:
    Egg(string _t):Food(_t)};
    virtual void eat() { // Delicious! };
    void unscramble();
}     

int main() {
    Food *ptr[2];
    ptr[0] = new Fruit("Apple");
    ptr[1] = new Egg("Brown");

    // Now, I want to call the unscramble() method on Egg.
    // Note that this method is unique to the Egg class.
    ptr[1]->unscramble();
    // ERROR: No member "unscramble" in Food

    cout << "\n\n";
    return 0;
}

Solution

  • If you are sure it is an Egg:

    static_cast<Egg*>(ptr[1])->unscramble();
    

    If you don't know whether it is an Egg:

    auto egg = dynamic_cast<Egg*>(ptr[1]);
    if (egg != nullptr)
        egg->unscramble();