I have found some code that I am working on, and was wondering what the best design implementation is.
If a base class defines a method as virtual, but implements an empty body as well, thus not requiring the derived classes to implement a body, should it not be made pure instead?
virtual void AMethod1() {} // 1
virtual void AMethod2() {assert(false);} // 2
virtual void AMethod3() = 0; // 3
- Current code.
- Idea1: Alerts user that this derived object has not implemented this method body.
- Idea2: Forces derived classes to implement a body, empty or not.
What do you, the trusted amazing SO people, think?
Edit1: After posting (and reading answers), I realize that assert is bad!
virtual void AMethod3() = {throw (ENotImplemented)}; // 4
assert
as worse than an exception? In the case at hand, I find it quite appropriate: if the method must always be overriden and the base class never instantiated, then the default implementation should never be called, this is an invariant of the program (not an event that can exceptionnaly occurs). Of course, if these are the requirements, you are better off making the method pure virtual. – Murrassert()
is checked in debug mode only, it is usually switched off in release build. – Dearythrow UnimplementedException
is more safe even in release code and much more readable than assertion. – Deary