Prevent derived classes from hiding non virtual functions from base

我与影子孤独终老i 提交于 2019-12-01 18:58:25

问题


Consider that I have classes A & B such that

class A
{
   public:
   void Fun();
};

class B  : public A
{
   ....
};

Is there any way that I as a designer of class A can enforce that derived class B and other classes which derive from A, are prevented(get a some kind of error) from hiding the non virtual function Fun()?


回答1:


If you want the non-virtual member function to always be accessible in some way, then simply wrap it in a namespace scope free function:

namespace revealed {
    void foo( A& o ) { o.foo(); }
}

now clients of class B can always do

void bar()
{
    B o;
    revealed::foo( o );
}

However, no matter how much class B introduces hiding overloads, clients can also just do

void bar2()
{
    B o;
    A& ah = o;
    ah.foo();
}

and they can do

void bar3()
{
    B o;
    o.A::foo();
}

so just about all that's gained is an easier-to-understand notation and intent communication.

I.e., far from being impossible, as the comments would have it, the availability is what you have by default…



来源:https://stackoverflow.com/questions/14997210/prevent-derived-classes-from-hiding-non-virtual-functions-from-base

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!