name hiding and fragile base problem

前端 未结 3 936
死守一世寂寞
死守一世寂寞 2020-12-03 14:41

I\'ve seen it stated that C++ has name hiding for the purposes of reducing the fragile base class problem. However, I definitely don\'t see how this helps. If the base class

3条回答
  •  离开以前
    2020-12-03 14:57

    I'll assume that by "fragile base class", you mean a situation where changes to the base class can break code that uses derived classes (that being the definition I found on Wikipedia). I'm not sure what virtual functions have to do with this, but I can explain how hiding helps avoid this problem. Consider the following:

    struct A {};
    
    struct B : public A
    {
        void f(float);
    };
    
    void do_stuff()
    {
        B b;
        b.f(3);
    }
    

    The function call in do_stuff calls B::f(float).

    Now suppose someone modifies the base class, and adds a function void f(int);. Without hiding, this would be a better match for the function argument in main; you've either changed the behaviour of do_stuff (if the new function is public), or caused a compile error (if it's private), without changing either do_stuff or any of its direct dependencies. With hiding, you haven't changed the behaviour, and such breakage is only possible if you explicitly disable hiding with a using declaration.

提交回复
热议问题