virtual function that is const in the base class and not const in the derived

后端 未结 6 1391
庸人自扰
庸人自扰 2021-02-08 09:54

Can anyone explain the output of the following code?

#include 
#include 
class Animal
{
public:
    Animal(const std::string &          


        
6条回答
  •  遇见更好的自我
    2021-02-08 10:21

    Cow isn't overriding the virtual function from Animal because it has a different signature. What's actually happening is that Cow is hiding the function in Animal.

    The result of this is that calling printMessage on an Animal will just use the version in Animal, regardless of the one in Cow (it isn't overriding it), but calling it from Cow will use the one in Cow (because it hides the one from Animal).

    To fix this, remove the const in Animal, or add the const in Cow.

    In C++ 2011, you will be able to use the override keyword to avoid subtle traps like this:

    class Cow : public Animal 
    { 
    public: 
        Cow(const std::string & name) : Animal(name) { } 
        ~Cow() { } 
        virtual void printMessage() override
        { 
            Animal::printMessage(); 
            std::cout << "and moo " << std::endl; 
        } 
    };
    

    Notice the added override after printMessage(). This will cause the compiler to emit an error if printMessage doesn't actually override a base class version. In this case, you would get the error.

提交回复
热议问题