Search code examples
c++friendooad

Remove friend class dependency in the following case


class foo
{
    bar b;

    someFunction()
    {
        b.alphaObj->someFunctionOfAlpha();
    }
};


class bar
{
    friend class foo;
    // many more friends

private:
    alpha *alphaObj;
};

How do I remove the friend dependency without exposing the private members with getters and setters. I understand friend classes could help in enhancing encapsulation but there are a lot of friend classes defined in my class exposing the private members to all. Hence I am thinking of a better approach and any help is appreciated.


Solution

  • Independent of your friend issue, being required to write this

    b.alphaObj->someFunctionOfAlpha();
    

    is not the best design. You should rather call (*):

    b.someFunctionOfAlpha();
    

    Now it is also obvious how to remove the friends:

    class bar
    {
    public:
        void someFunctionOfAlpha() { alphaObj->someFunctionOfAlpha(); }
    
    private:
        alpha *alphaObj;
    };
    

    (*) This guideline has a name, I just cannot find it at the moment. In general, calling a method should be like: "Do that!". Calling a method should not be like "Show me your internals so I can do what I want".