Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the potential danger of overriding a private function to public?

I just find out that overriding a private function to a public one from base object is allowed in C++ since Visual Studio produces 0 warning. Is there any potential danger to doing that?

If there isn't, what's the difference between declaring a virtual function in private, protected and public in a base object?

like image 735
Rahn Avatar asked Oct 20 '22 02:10

Rahn


1 Answers

what's the difference between declaring a virtual function in private, protected and public in a base object?

The difference is that a private virtual function can be called only from a base class. This can be useful if the function is not a part of an external class interface, and is only used by base class. So that users call (some other) base class' member, and that member calls the virtual function. For example:

class Base {
    virtual void stage1()=0;  // derived classes override this
    virtual void stage2()=0;
  public:
    void run() { stage1(); stage2(); } // users call this
};

Moreover, there is a point of view that you should not make your virtual functions public at all, because the fact that they are virtual is internals of the class and its subclasses, and the users should not be aware of that. It is rarely that the same function must be overridden and callable from external code. This allows the base class to control which (virtual) functions can be called from which (non-virtual) public method, making maiteinance easier.

See more details in this article by Herb Sutter:

...each [public] virtual function is doing two jobs: It's specifying interface because it's public...; and it's specifying implementation detail, namely the internally customizable behavior... That a public virtual function inherently has two significantly different jobs is a sign that it's not separating concerns well and that we should consider a different approach. What if we want to separate the specification of interface from the specification of the implementation's customizable behavior?

...

In summary, prefer to make base class virtual functions private (or protected if you really must). This separates the concerns of interface and implementation, which stabilizes interfaces and makes implementation decisions easier to change and refactor later.

However, I am not qualified to say whether this is really widely used...

like image 166
Petr Avatar answered Oct 21 '22 16:10

Petr