Search code examples
c++pure-virtual

Does it make any sense to define "pure" virtual functions in the base class itself?


The benefit of defining common virtual functions in the base class is that we don't have to redefine them in the derived classes then.

Even if we define pure virtual functions in the base class itself, we'll still have to define them in the derived classes too.

#include <iostream>
using namespace std;

class speciesFamily
{
    public:
        virtual void numberOfLegs () = 0;
};

void speciesFamily :: numberOfLegs ()
{
    cout << "\nFour";
}

class catFamily : public speciesFamily
{
    public:
        void numberOfLegs ()
        {
            speciesFamily :: numberOfLegs ();
        }
};

This may look fancy for sure, but are there any situations when it is beneficial to define a pure virtual function in the base class itself?


Solution

  • are there any situations when it is beneficial to define a pure virtual function in the base class itself?

    Yes - if the function in question is the pure virtual destructor, it must also be defined by the base class.