Why does C++ not allow inherited friendship?

前端 未结 10 1574
终归单人心
终归单人心 2020-11-28 04:11

Why is friendship not at least optionally inheritable in C++? I understand transitivity and reflexivity being forbidden for obvious reasons (I say this only to head off sim

10条回答
  •  借酒劲吻你
    2020-11-28 04:33

    Because it's just unnecessary.

    The usage of the friend keyword is itself suspicious. In term of coupling it's the worst relationship (way ahead of inheritance and composition).

    Any change to the internals of a class have a risk to impact the friends of this class... do you really want an unknown number of friends ? You would not even be able to list them if those who inherit from them could be friends also, and you would run in the risk of breaking your clients code each time, surely this is not desirable.

    I freely admit that for homework/pet projects dependency is often a far away consideration. On small size projects it doesn't matter. But as soon as several persons work on the same project and this grows into the dozens of thousands of lines you need to limit the impact of changes.

    This bring a very simple rule:

    Changing the internals of a class should only affect the class itself

    Of course, you'll probably affect its friends, but there are two cases here:

    • friend free function: probably more of a member function anyway (I am think std::ostream& operator<<(...) here, which is not a member purely by accident of the language rules
    • friend class ? you don't need friend classes on real classes.

    I would recommend the use of the simple method:

    class Example;
    
    class ExampleKey { friend class Example; ExampleKey(); };
    
    class Restricted
    {
    public:
      void forExampleOnly(int,int,ExampleKey const&);
    };
    

    This simple Key pattern allows you to declare a friend (in a way) without actually giving it access to your internals, thus isolating it from changes. Furthermore it allows this friend to lend its key to trustees (like children) if required.

提交回复
热议问题