3

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!

Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467
Without Me It Just Aweso
  • 4,593
  • 10
  • 35
  • 53

2 Answers2

8

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
  • 554,122
  • 78
  • 1,158
  • 1,373
  • 1
    Make sure you take note that you'll need to refer to any forward-declared types using pointers or references as shown in this example (b& temp). – Ron Warholic Mar 23 '10 at 20:56
  • 6
    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 Mar 23 '10 at 21:03
2

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

Tuomas Pelkonen
  • 7,783
  • 2
  • 31
  • 32