Overriding public virtual functions with private functions in C++

前端 未结 7 577
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 02:51

Is there is any reason to make the permissions on an overridden C++ virtual function different from the base class? Is there any danger in doing so?

For example:

7条回答
  •  無奈伤痛
    2020-11-27 03:19

    You do get the surprising result that if you have a child, you can't call foo, but you can cast it to a base and then call foo.

    child *c = new child();
    c->foo; // compile error (can't access private member)
    static_cast(c)->foo(); // this is fine, but still calls the implementation in child
    

    I suppose you might be able to contrive an example where you don't want a function exposed, except when you are treating it as an instance of the base class. But the very fact that that situation pops up would suggest a bad OO design somewhere along the line that should probably be refactored.

提交回复
热议问题