Public virtual function derived private in C++

前端 未结 3 718
离开以前
离开以前 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: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".

提交回复
热议问题