views:

155

answers:

2

It's been a long time since I've done C++ and I'm running into some trouble with classes referencing each other.

Right now I have something like:

a.h

class a
{
  public:
    a();
    bool skeletonfunc(b temp);
};

b.h

class b
{
  public:
    b();
    bool skeletonfunc(a temp);
};

Since each one needs a reference to the other, I've found I can't do a #include of each other at the top or I end up in a weird loop of sorts with the includes.

So how can I make it so that a can use b and vice versa without making a cyclical #include problem?

thanks!

+8  A: 

You have to use Forward Declaration:

a.h

class b;
class a
{
  public:
    a();
    bool skeletonfunc(b temp);
}

However, in many situations, this can force you to work with references or pointers in your method calls or member variables, since you can't have the full types in both class headers. If the size of the type must be known, you need to use a reference or pointer. You can, however, use the type if only a method declaration is required.

Reed Copsey
Ron Warholic
No, the original declaration (with pass-by-value semantics) would compile. You will need the full class declaration before the method definition, but not to declare the method signature: `class a; void f( a ); class a {}; void f(a x) {...` see http://stackoverflow.com/questions/389957/forward-declaration-of-a-base-class/390124#390124
David Rodríguez - dribeas
@David: I edited to be more explicit about that.
Reed Copsey
+2  A: 

Use forward declaration : http://en.wikipedia.org/wiki/Forward_declaration

Tuomas Pelkonen