How to use virtual functions to achieve a polymorphic behavior in C++?

后端 未结 1 1604
星月不相逢
星月不相逢 2021-01-25 04:34

I am new to these important features of C++, i have already read a few question/answers on these topics here and googled a few docs. But i am still confused with this...

<
相关标签:
1条回答
  • 2021-01-25 04:46

    Here's the best explanation of polymorphism that I've ever heard:

    There are many animals in this world. Most of them make some sound:

    class Animal
    {
    public:
        virtual void throwAgainstWall() { };
    };
    
    class Cat : public Animal
    {
    public:
        void throwAgainstWall(){ cout << "MEOW!" << endl; }
    };
    
    class Cow : public Animal
    {
    public:
        void throwAgainstWall(){ cout << "MOOO!" << endl; }
    };
    

    Now imagine you have huge bag with animals and you can't see them. You just grab one of them and throw it against wall. Then you listen to its sound - that tells you what kind of animal it was:

    set<Animal*> bagWithAnimals;
    bagWithAnimals.insert(new Cat);
    bagWithAnimals.insert(new Cow);
    
    Animal* someAnimal = *(bagWithAnimals.begin());
    someAnimal->throwAgainstWall();
    
    someAnimal = *(bagWithAnimals.rbegin());
    someAnimal->throwAgainstWall();
    

    You grab first animal, throw it against wall, you hear "MEOW!" - Yeah, that was cat. Then you grab the next one, you throw it, you hear "MOOO!" - That was cow. That's polymorphism.

    You should also check Polymorphism in c++

    And if you are looking for good book, here is good list of 'em: The Definitive C++ Book Guide and List

    0 讨论(0)
提交回复
热议问题