Public virtual function derived private in C++

前端 未结 3 719
离开以前
离开以前 2020-12-04 22:36

I was trying to figure out what happens when a derived class declares a virtual function as private. The following is the program that I wrote

#include 

        
相关标签:
3条回答
  • 2020-12-04 23:01

    This is well-defined behavior. If a were a B* this wouldn't compile. The reason is that member access is resolved statically by the compiler, not dynamically at run-time. Many C++ books suggest that you avoid coding like this because it confuses less experienced coders.

    0 讨论(0)
  • 2020-12-04 23:03

    The behavior is correct. Whenever you declare your function as "virtual", you instruct the compiler to generate a virtual call, instead of the direct call to this function. Whenever you override the virtual function in the descendant class, you specify the behavior of this function (you do not change the access mode for those clients, who rely on the "parent's" interface).

    Changing the access mode for the virtual function in the descendant class means that you want to hide it from those clients, who use the descendant class directly (who rely on the "child's" interface).

    Consider the example:

    void process(const A* object) {
       object->func();
    }
    

    "process" function relies on the parent's interface. It is expected to work for any class, public-derived from A. You cannot public-derive B from A (saying "every B is A"), but hide a part of its interface. Those, who expect "A" must receive a fully functional "A".

    0 讨论(0)
  • 2020-12-04 23:16

    Well, you are calling A::func() which is public though in a B object it is overridden by B::func(). This is a common pattern with the following implications:

    • func is not intended to be called on derived B objects

    • func cannot be overridden in classes derived from B

    0 讨论(0)
提交回复
热议问题