Is there any valid reason for not using public virtual methods?
I have read somewhere that we should avoid using public virtual methods, but I want to confirm from experts if this is valid statement?
For good and stable API design, the Non-Virtual-Interface is a good idiom.
I'm going to defer to the existing good literature on this:
See also these splendid answers:
(Sumant Tambe has an intriguing matrix of Design Intent Implications on his blog, which has a few more bits on design intent.)
Making virtual
functions non-public allows the base class to create a protocol around them. If nothing else, this could be used for some accounting/profiling requiring instrumentation of only the base class. The base class public interface could be inline
functions merely forwarding to the virtual
functions. Sadly the restrictions can be relaxed in derived classes, i.e., a derived class may give public access to a virtual
function from the base class.
There is actually another important reason for making virtual
functions protected
: when overloading virtual
functions (e.g., the do_put()
members in std::num_put<...>
) it is easy to accidentally hide other overloads when overriding just one of the functions. When the virtual
functions is both the customization point as well as the call interface, this can easily lead to surprising behavior. When the virtual
functions are protected
it is clear that the call interface and the customization interfaces are actually different and the problem is avoided even when using the derived class directly. The virtual
functions probably want to be protected
to allow overriding functions to call the default implementation from the base class. If there is no default implementation, the virtual
function can also be private
.
This answer discusses why virtual
functions shouldn't be public
. Whether you should have virtual
functions in the first place is a separate question with a somewhat non-trivial answer.
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