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

最后都变了- 提交于 2019-12-03 11:22:52

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.

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 */ }

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.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!