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
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
A virtual function is a member function of base class which can be redefined by derived class. A pure virtual function is a member function of base class whose only declaration is provided in base class and should be defined in derived class otherwise derived class also becomes abstract.
When destroying instances of a derived class using a base class pointer object, a virtual destructor is used to free up memory space allocated by the derived class object or instance.
A pure virtual function or pure virtual method is a virtual function that is required to be implemented by a derived class if the derived class is not abstract. Classes containing pure virtual methods are termed "abstract" and they cannot be instantiated directly.
4. Which is the correct statement about pure virtual functions? Explanation: A pure virtual function does not have a definition corresponding to base class. All derived class may or may not have an implementation of a pure virtual function.
It depends a bit on how "pure" your coding style is. Some people believe that you should always define an interface with pure virtual functions only and derive all concrete classes from that.
Others are more pragmatic and belive that if there is a good default implementation, you can add that to the base class (option 1).
The second option seems to be the least useful, as it delays detection until runtime. Most programmers would rather prefer a compilation error from option 3.
As usual, C++ supports several paradigms and you can choose the one you prefer.
You should use option 3 if the derived class must implement this method. Use option 1 if implementing in the derived class is optional. Avoid option 2 altogether.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With