Is there a way to add a virtual function that must be overridden by all inherited classes? So actually the combination of virtual and abstract?
I have a situation where each inherited class must do some specific processing before some generic code is executed. Virtual functions doesn’t work because they do not ensure the inherited classes override them. And abstract function can’t have a default implementation. Currently my workaround is to implement another protected function in the base class which contains the common/generic code and is called in the overridden abstract function
Is there a way to add a virtual function that must be overridden by
Share
It is not possible to have a method that is both abstract and virtual.
If possible, you can split your method in a “before” and “after” part:
Otherwise, your workaround with a second protected method is a very good idea:
You can check if DoCommonWork was really called in DoWork using a thread-local field if necessary.
However, I’d probably go with making the method virtual. If the derived class doesn’t want to add anything to the common part, it shouldn’t have to:
Again, you can check if the common part was really called.