Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any valid reason for not using public virtual methods? [closed]

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?

like image 615
user3201542 Avatar asked Dec 12 '22 06:12

user3201542


2 Answers

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:

  • Herb Sutter: http://www.gotw.ca/publications/mill18.htm
  • More C++ Idioms/Non_Virtual_Interface

See also these splendid answers:

  • What is the point of a private pure virtual function?
  • Call a C++ base class method automatically
  • Best way to declare an interface in C++11
  • How to ensure that virtual method calls get propagated all the way to the base class?
  • What's the advantage of this indirect function call?

(Sumant Tambe has an intriguing matrix of Design Intent Implications on his blog, which has a few more bits on design intent.)

like image 200
sehe Avatar answered Apr 27 '23 12:04

sehe


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.

like image 32
Dietmar Kühl Avatar answered Apr 27 '23 12:04

Dietmar Kühl