How to have classes reference each other

My project currently does not build, and I believe the reason is this:

Class A has a local variable which is a pointer to Class B. Naturally I must #include "classB.h" in class A to declare this variable. However, Class B has a constructor which has a Class A pointer passed to it, so to declare this method prototype it must #include "classA.h". Now the code will not compile, since they both include each other and the constructor definition in Class B will occur before class A has been declared, so I get the error:

"error: expected ‘;’ before ‘*’ token"

on the line which declares the Class B pointer.

What is the appropriate way to get around this issue?

Thanks in advance.
Your assessment of the problem is correct, however you don't have to include classB.h in classA.h or vice versa.

Use forward declarations:

File: classA.h:
1
2
3
4
5
6
7
8
9
10
#ifndef CLASSA_H
#define CLASSA_H

class B;   // forward declaration

class A {
   B* pB;
};

#endif 


When you only refer to a type by reference or by pointer, you do not need to include it's header file; rather you can forward declare.
Topic archived. No new replies allowed.