Search code examples
c++classobjectfriendnested-class

C++: Friend specific objects (nested classes)


Say I have a class called class AI. And inside this class I created another child class called class AIbrain. Now, I want each separate AI object to be able to operate their own AIbrain. But if I class AIbrain{friend AI;}; the class Aibrain will be exposed to every object of the class AI.

So I was wondering is there a way of an AIbrain friending their own AI object? Or else each AI will be able to modify any other AI's variables and access their functions.


Solution

  • I hope I understood you correctly:

    class AI
    {
        class AIbrain
        {
        } brain;
    };
    

    You want brain to be able to access its parent instance of AI (code examples make a lot clearer what you want to achieve by the way).

    If this is the case you could solve this by:

    class AI
    {
            class AIbrain
            {
                    AI * parent_;
                    explicit AIbrain(AI * parent) : parent_(parent) {}
            } brain;
    
        public:
             AI() : brain(this) {}
    };
    

    If brain needs to access private members of the AI parent instance, you still need to declare AIbrain as a friend of AI. Since AIbrain is a member of AI, it is not necessary to declare AI a friend of AIbrain. Note that this is used here as a trick to prevent users from instantiating AIbrain directly (private constructor is accessable only for AI).