Can we override pure virtual functions from inherited class?

1.7k views Asked by At

I have an interface class – IAnimal and 2 derived classes – Tcat and Tdog. I want both Tcat and Tdog to inherit the Eat function, however, I want Tcat to be able to have 2 parameters and Tdog to have the parameters that it inherits. Is this possible?

/// Pure virtual - to ensure all inherited animals have eat and sleep
class IAnimal
{
public:
    virtual ~IAnimal() {}
    virtual bool Eat(int _i_food) = 0;
    virtual bool Sleep(int _i_time) = 0;
};

class TCat : public IAnimal
{
public:
    bool Eat(int _i_food, int _i_amount); // can we override interface pure virtual from inherited class? 
    bool Sleep(int _i_time);
};

class TDog : public IAnimal
{
public:
    bool Eat(int _i_food);
    bool Sleep(int _i_time);
};
4

There are 4 answers

0
nvoigt On

No

This is not possible. And it would not make sense either, because if those functions have a different signature, you would not be able to call them through the interface. What should happen if you pass one parameter through the interface and the actual instance needs two?

What you can do is override the one that you have to and then add an additional method with two parameters. But you will not be able to call the new one through the interface.

0
pSoLT On

You need to provide implementation all pure virtual functions. You can override the function Eat(int _i_food) but it won't be possible to invoke the overloaded version using pointer to base class.

0
CashCow On

Your problem is that the Eat method in TCat is not an override of the method in its base class but an overload, and it "hides" the base class method.

See this question:

Why does a virtual function get hidden?

0
iammilind On

No. Signature of a virtual method can't be altered. Not even with default parameters.
The only exception is the covariance, where the return type can be different.

With C++11, the rule of thumb is to put override specifier after the supposed virtual method (either pure or not). If it doesn't compile, then something is wrong. In your code example, following will fail to compile:

bool Eat(int _i_food, int _i_amount) override;  // error