Search code examples
c++overridingconstantsvirtualmember-functions

Overriding virtual member function containing constant


How can I override a virtual member function of the following type:

virtual AnimalId func(int index) const

where AnimalId is a typedef unsigned int

I tried several ways but either ending up by an error that I don't give output or that I don't have an overrider at all. I saw on some website that maybe I need to use static const in order to do this, but I don't know how.


Solution

  • In order to override method of signature

    virtual AnimalId func(int index) const
    

    declared in base class Base, you have to define function with same signature in derived class:

    class Derived : public Base {
    public:
       virtual AnimalId func(int index) const
         {
             return 43;  // I am using 43 because I think this is
                         // so much underestimated in favor of 42
         }
        //...
    };
    

    Or you can type override kryword to be more explicit:

    class Derived : public Base {
    public:
       virtual AnimalId func(int index) const override
         {
             return 43 & 45;
         }
        //...
    };