Why do we need virtual functions in C++?

前端 未结 26 3179
北恋
北恋 2020-11-21 05:50

I\'m learning C++ and I\'m just getting into virtual functions.

From what I\'ve read (in the book and online), virtual functions are functions in the base class that

26条回答
  •  无人及你
    2020-11-21 05:59

    You need at least 1 level of inheritance and an upcast to demonstrate it. Here is a very simple example:

    class Animal
    {        
        public: 
          // turn the following virtual modifier on/off to see what happens
          //virtual   
          std::string Says() { return "?"; }  
    };
    
    class Dog: public Animal
    {
        public: std::string Says() { return "Woof"; }
    };
    
    void test()
    {
        Dog* d = new Dog();
        Animal* a = d;       // refer to Dog instance with Animal pointer
    
        std::cout << d->Says();   // always Woof
        std::cout << a->Says();   // Woof or ?, depends on virtual
    }
    

提交回复
热议问题