Does it make any sense to define “pure” virtual fu

2020-06-10 15:55发布

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?

4条回答
趁早两清
2楼-- · 2020-06-10 16:12

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.

查看更多
放我归山
3楼-- · 2020-06-10 16:17

It can be beneficial when there is no reasonable implementation of pure virtual function can be in base class. In this case pure virtual functions are implemented in derived classes.

查看更多
淡お忘
4楼-- · 2020-06-10 16:20

Two things:

First off, there's one border-line scenario which is commonly cited: Suppose you want an abstract base class, but you have no virtual functions to put into it. That means you have no functions to make pure-virtual. Now there's one way around: Since you always need a virtual destructor, you can make that one pure. But you also need an implementation, so that's your canditate:

struct EmptyAbstract
{
  virtual ~EmptyAbstract() = 0; // force class to be abstract
};
EmptyAbstract::~EmptyAbstract() { } // but still make d'tor callable

This may help you minimize the implementation size of the abstract class. It's a micro-opimization somehow, but if it fits semantically, then it's good to have this option.

The second point is that you can always call base class functions from derived classes, so you may just want to have a "common" feature set, despite not wanting any abstract instances. Again, in come pure-virtual defined functions:

struct Base
{
  virtual void foo() = 0;
};

struct Derived : Base
{
  virtual void foo()
  {
    Base::foo();  // call common features
    // do other stuff
  }
};

void Base::foo() { /* common features here */ }
查看更多
贼婆χ
5楼-- · 2020-06-10 16:22

A base-class with only pure virtual functions are what languages like Java would call an interface. It simply describes what functions are available, nothing else.

查看更多
登录 后发表回答