0

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?

Ehsan Khodarahmi
  • 4,772
  • 10
  • 60
  • 87
  • possible duplicate of [cyclic dependency between header files](http://stackoverflow.com/questions/2089056/cyclic-dependency-between-header-files) – RedX Jun 28 '12 at 09:59
  • Search for forwad declare and cyclic header dependency. There are tons of questions about that on stackoverflow. – RedX Jun 28 '12 at 10:00

2 Answers2

6

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.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
0

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.

Branko Dimitrijevic
  • 50,809
  • 10
  • 93
  • 167