Prevent derived classes from hiding non virtual functions from base

前端 未结 1 1090
盖世英雄少女心
盖世英雄少女心 2021-01-19 11:47

Consider that I have classes A & B such that

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

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

Is there any way

相关标签:
1条回答
  • 2021-01-19 12:18

    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…

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