1

Possible Duplicate:
Resolve circular dependencies in c++
What is forward declaration in c++?

I have two classes A and B. I need to have a field in each which is a pointer to an object of the other class. I get "does not name a type" since the definition of the class is yet to appear. For example:

class A{
   B* b;
}
class B{
   A* a;
}

gets me "B "does not name a type" at the second line.

Community
  • 1
  • 1
SrSbSd
  • 219
  • 2
  • 4
  • 11

2 Answers2

3

Use forward declarations:

class B;

class A {
  B* b;
};

class B {
  A* a;
};

This way you're telling the compiler that B is going to be declared later on and that it should not worry. See this for more info: Forward declaration

Community
  • 1
  • 1
Adri C.S.
  • 2,909
  • 5
  • 36
  • 63
1

Forward declarations is key to you question , here is the link

What is forward declaration in c++?

Community
  • 1
  • 1
Paritosh
  • 2,303
  • 2
  • 18
  • 24