Ehsan Khodarahmi
Ehsan Khodarahmi

Reputation: 4922

Cyclic class dependency while including header files in C++

I'm developing a C++ program using visual studio 2010. I've these class definitions & header files :
s.h :

class s : oe {
    ...
};

t.h :

class t : oe {
    ...
};

oe.h :

class oe {
    ...
    o getO();//we reference to class 'o' in oe.h, so we must include o.h begore oe.h
};

& o.h :

class o {
    ...
    s getS();//we reference to class 's' in o.h, so we must include s.h begore o.h 
};

the problem is that we reference to class 'o' in oe.h, so we must include o.h before oe.h, & also we reference to class 's' in o.h, so we must include s.h before o.h, but we can't do this because s.h needs oe.h & oe.h needs o.h & o.h needs s.h !
As you see, some kind of loop exists in class dependency cycle & so I can't compile the project. If i remove dependency between s.h & t.h & oe.h, the problem will solve (here is stdafx.h for this state) :

#include "s.h"
#include "t.h"
#include "o.h"
#include "oe.h"

but I have to use all given dependencies & I can't remove anyone of dependencies. any idea?

Upvotes: 0

Views: 1710

Answers (2)

Branko Dimitrijevic
Branko Dimitrijevic

Reputation: 52107

Forward declarations will work not only for pointers/references by for return values as well.

So, you can do something like this:

oe.h:

class o;

class oe {
    o getO();
};

oe.cpp:

#include "oe.h"
#include "o.h"

o oe::getO() {
    return o();
}

Rinse and repeat as necessary... Since you no longer have #includes in the .h files, there is no opportunity for circular include dependencies.

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258568

You can solve this using forward declarations instead and moving implementations to implementation files.

Instead of including a header for s, just forward declare it:

class s;

and you can use it as an incomplete type for just about anything except a data member of the class. (provided the implementations are separated).

This, most probably, doesn't tackle the underlying problem, which is your design.

Upvotes: 6

Related Questions