skittles sour
skittles sour

Reputation: 537

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.

Upvotes: 1

Views: 159

Answers (2)

nikolas
nikolas

Reputation: 8975

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).

Upvotes: 3

doctorlove
doctorlove

Reputation: 19262

You don't modify the variables and functions of a class (unless they are static) you modify those of an instance.
If you simple want each AI to have a AIBrain, give each AI instance an AI member

class AIBrain { /*...*/ };
class AI {
  public:
  //whatever
  private:
    AIBrain brain;
};

Each AI instance then has its own brain and can use the brain's public members and functions.

Upvotes: 2

Related Questions