Link to home
Start Free TrialLog in
Avatar of Zainal062797
Zainal062797

asked on

Circular Definitions

I have a number of header files that are dependent on each other. For example, the defintion of object A contains a reference to the defintion of object B. And the defintion of object B contains a reference to the defintion of object A. Object A and B are in different files. I have tried to solve the problem by doing the following in the first file:

class B;
class A
{
B objectB;
}

And doing the following in the other file:
class A;
class B
{
A objectA;
}

But the problem is still not solved!!
What am I suppose to do to solve this problem?

Thank you.
ASKER CERTIFIED SOLUTION
Avatar of MT_MU
MT_MU

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of tao_shaobin
tao_shaobin

The reasons why it works after we change them to pointers are:

B* objectB; is only a declaration.  It won't call anything, including construtors of B.  But B objectB; may call the construtor which may initialize some variables.  

In this case, it is impossible to declare circular declarations if both classes need to initialize some variables in their construtors.  Therefore, we need to prevent this to happen.  If not of all of them need initilization, then you can declare like this(suppose A needs not to initialize)

a.h

#include "B.h"  // only way
class A
{
  B  bobject;
  ....
{

b.h

class A;
class B
{
  A aObject;
  ....
}

Then, your program should work.

Help this helps,

tao_shaobin