Ezio A
Ezio A

Reputation: 125

Problems with circular dependency

I have tried to solve the problems related to circular dependency in some files I have made following that structure:

A.h

#include "B.h"
#include "C.h"
#include "D.h"

namespace NS {

class B;
class C;
class D;

class A {

/* ... */

    A(const A& a) {};

    A(const B& a) {};
    A(const C& a) {};
    A(const D& a) {};

/* ... */
};

}; // NS END

B.h

#include "A.h"
#include "C.h"
#include "D.h"

namespace NS {

class A;
class C;
class D;

class B {

/* ... */

    B(const B& a) {};

    B(const A& a) {};
    B(const C& a) {};
    B(const D& a) {};

/* ... */
};

}; // NS END

C.h

#include "A.h"
#include "B.h"
#include "D.h"

namespace NS {

class A;
class B;
class D;

class C {

/* ... */

    C(const C& a) {};

    C(const A& a) {};
    C(const B& a) {};
    C(const D& a) {};

/* ... */
};

}; // NS END

D.h

#include "A.h"
#include "B.h"
#include "C.h"

namespace NS {

class A;
class B;
class C;

class D {

/* ... */

    D(const D& a) {};

    D(const A& a) {};
    D(const B& a) {};
    D(const C& a) {};

/* ... */
};

}; // NS END

Whatever I try I have some errors from the constructors taking as argument classes in other files, even putting the declaration ahead, seems like it take it the declaration as declaration and definition, and ignore the real definition that is in another file. How could I solve that?

NOTE: I have define guard in each file, just I didnt put it here

Upvotes: 0

Views: 277

Answers (3)

DRVic
DRVic

Reputation: 2491

In addition, it is always a good idea to add #include guards as follows:

#ifndef _INCLUDED_A_H #define _INCLUDED_A_H

.... < here are the normal contents of your header file > ....

#endif

But the main thing is, as stijn pointed out, when you have forward declarations you don't need to include the full definitions as well.

Upvotes: 0

linello
linello

Reputation: 8714

forward declarations! If you are not using classes methods, forward declarations can help you to disentangle the dependencies.

http://www-subatech.in2p3.fr/~photons/subatech/soft/carnac/CPP-INC-1.shtml

Upvotes: 0

stijn
stijn

Reputation: 35901

if you remove all the #includes in the headers and put them in the source files, everything should compile.

You don't need the includes since you have forward declarations which is sufficient in this case since you only use const references to the forward declared classes. (note: previous statements only hold if your sample code mimics your actual code).

You can also add a seperate header forward.h containing the declarations, instead of repeating yourself everywhere:

namesapce NS
{
  class A;
  class B;
  class C;
  class D;
}

Now make A.h, B.h etc #include forward.h and you do not need the forward declarations in each header anymore.

Upvotes: 4

Related Questions