When one class has object of another class as data member and vise-versa.

Suppose I have class A:
1
2
3
4
5
6
7
8
9
10
//A.h
class A
{
  protected:
    std::vector<B> bList;

  public:
    //some stuff with bList
};
[

You see that it requires the definition of class B. On the other hand:
1
2
3
4
5
6
7
8
9
//B.h
class B
{
  protected:
    const A* a;

  public:
    //some stuff with a
};

You can see some kind of loop because the B class requires the definition of A
I have some compilation errors but this fragment of code is actually only a part of big stuff and I am not sure the errors are due to this loop.
Is it wrong to do so? And if so, how to bypass this design flaw?
Last edited on
forward declare
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
in A.h
class B; //declaration
class A{ //definition
};

//in B.h
class A; //declaration
class B{ //definition
   //...
};

//in A.cpp
#include "A.h"
#include "B.h"

//methods that use B 
you can still declare the member functions inline, but put their definition outside the class.
Topic archived. No new replies allowed.