0

I know there is one case you might want to provide a definition for a pure virtual function. According to effective c++ by Scott Meyers, If you want an abstract class which is used as base class but does not have any other functions, you may need to provide a definition for its pure destructor like this:

class abstract_base_class_do_nothing{
public : 
    virtual ~abstract_base_class_do_nothing() = 0;
}
abstract_base_class_do_nothing::~abstract_base_class_do_nothing(){}

You provide this because subclass need to call its dtor, and you can't override base class's dtor in derived classes.

Apart to this situation, are there any reasons that you should provide a definition for a pure virtual function? (Of course, overriding it in derived class does NOT count). I mean, even if you provide it, it may never get called by polymorphism anyway.

Thanks!

I just wonder why c++ allow definition for pure virtual functions.

Han XIAO
  • 1,148
  • 9
  • 20
  • There is nothing preventing it from being called. Derived classes may still call it in the same manner as virtual destructor. Though I can't really think of any situation when this would make sense, – user7860670 Jul 22 '18 at 12:41
  • @VTT Yeah, thanks! In derived class I can call it using the base class namespace prefix. – Han XIAO Jul 22 '18 at 12:43
  • Any pure virtual function other than a constructor may be defined if the designer of the base class needs to provide a default implementation that can be called *statically* (either within the class or by derived classes) but also force derived classes to override it. – Peter Jul 22 '18 at 12:44
  • I suggest you pick up Scott Meyers' Effective C++. IIRC there's an item there that discusses rationale for providing definitions to pure virtual members, as opposed to just defining them as "regular" virtual members. – StoryTeller - Unslander Monica Jul 22 '18 at 12:47
  • @StoryTeller Thanks! Haha, I sorrily mistyped his name. – Han XIAO Jul 22 '18 at 12:48

0 Answers0