c++class

How to create a class setup where two classes each holds an instance of the other?


I have a class setup like this, where each class holds a member of the other one:

class b;

class a
{
    b var;
};

class b
{
    a var;
};

How do I make it work?


Solution

  • This setup, as it's written, isn't possible - an instance of a contains an instance of b, which in turn contains an instance of a, which then contains an instance of b, ad infinitum.

    Instead, you need the classes to hold pointers to each other:

    class a {
       b* b;
    };
    
    class b {
       a* a;
    };