Avoiding predeclaration with codependent headers

Is there a good/proper way to get around this? It seems like I'm doing something wrong.

first.h
#ifndef FIRST_H
#define FIRST_H
#include "second.h"
class Second;
class First
{
Second* secondptr;
First();
};
#endif

first.cpp
#include "first.h"
First::First()
{
secondptr = new Second(*this);
}

second.h
#ifndef SECOND_H
#define SECOND_H
#include "first.h"
class First;
class Second
{
First* firstptr;
public:
Second(First& first_ref);
};
#endif SECOND_H

second.cpp
#include "second.h"
Second::Second(First& first_ref)
{
firstptr = &first_ref;
}
You don't need to include any header in the other if you are forward declaring the classes
My compiler seems to think so, it can't find any methods of the other class:

first.cpp(5) : error C2514: 'Second' : class has no constructors

The same thing seems to go for classes within the same header, which is more reasonable but when they are mixed from other header classes it gets messy.

#ifndef FIRST_H
#define FIRST_H
#include "second.h"
class Second;
class Third;
class First
{
Third* thirdptr;
First();
public:
Second* secondptr;
};
class Third
{
First* firstptr;
public:
Second* secondptr;
Third(First& first_ref);
};
#endif
Don't include the file in the .h(pp) if you are forward declaring the classes there. Include it in the .cpp instead.
Okay that might make things look a little better. I've just been told that it's not a good idea to predeclare classes like that, not sure what reasons behind it.

I suppose then I would arrange things like this (cases are a Second class mutually included from another .h/.cpp module, a Third class mutually included in same .h/.cpp module, and a Foo class not-mutually included in another .h/.cpp module):
first.h
#ifndef FIRST_H
#define FIRST_H
class Foo;
class Second;
class Third;
class First
{
Foo* fooptr;
Third* thirdptr;
First();
public:
Second* secondptr;
};
class Third
{
First* firstptr;
public:
Second* secondptr;
Third(First& first_ref);
};
#endif

first.cpp
#include "first.h"
#include "foo.h"
#include "second.h"
First::First()
{
fooptr = new Foo;
secondptr = new Second(*this);
thirdptr = new Third(*this);
secondptr->thirdptr = thirdptr;
}
Third::Third(First& first_ref)
{
firstptr = &first_ref;
secondptr = firstptr->secondptr;
}

foo.h
#ifndef FOO_H
#define FOO_H
class Foo
{
bool bar;
public:
Foo();
};
#endif

foo.cpp

#include "foo.h"
Foo::Foo()
: bar (true)
{
}


I guess the thing about that is if I have a class that is included in many other modules I have to #include it in each .cpp file instead of a central file like first.h
Obligatory link:

http://cplusplus.com/forum/articles/10627/#msg49679

See section 4 and up.
Topic archived. No new replies allowed.