views:

41

answers:

3

This may seem weird but I have a problem in one of my programs where I have a class A which needs a variable of class B inside it, and the class B needs a pointer to class A inside it, so that i can determine which class is attached to what....

i get errors because in class A it says that the class B is not defined yet, and in class B it says class A isn't defined yet...

both of my header files which contain the separate classes include each other and i have tried to forward declare my classes e.g. class A; class B; but i get compiler errors such as:

error C2079: 'CFrame::menu' uses undefined class 'CMenu'

I need a pointer to classA in class B because i want to pass it to another class later on

+5  A: 

You need to declare A before you define B:

class A;   // declaration of A

class B    // definition of B
{
    A* foo;
    // ...
};

class A    // definition of A
{
    B bar;
    // ...
};

This kind of declaration is often referred to as a forward declaration.

FredOverflow
The point is that you only use the forward declaration for B, not for A, since A contains and instance variable of type B rather than a pointer.
Paul Keister
Ah yes, i have a big mess here, i actually did this to start with but i've realise that my "safety guards" eg. #ifndef CMENU_INCLUDED#define CMENU_INCLUDED, were messing it up, so i included that one header BEFORE them, and did just ONE forward declare, now it works! thanks
It relies on 3.9.2/3 - "Pointers to incomplete types are allowed although there are restrictions on what can be done with them (3.9).". Therefore it is legitimate to have a pointer to B, even if B is incomplete at that point
Chubsdad
+2  A: 

First of all, consider redesigning your classes. Circular dependencies are bad practice, and chances are that you could avoid this altogether with a more elegant class design.

That said, you can get around the problem using forward references (at which point, you need to use pointers or references) -

class B;

class A
{
   B *pPtr;
};

class B
{
   A typeA;
};
EboMike
A: 

You may be able to avoid forward declaration by simply specifying what a "B" is:

class A
{
public:
  class B* pB;
};

class B
{
public:
  A a;
};

If you're having problems with this, it may be because you're including implementation along with your declarations. If you separate the implementation and the header, you might have fewer problems in this scenario.

Merlyn Morgan-Graham