views:

41

answers:

1

I have this situation (two classes with two different header files):

b.h

#include "a.h"

class B {
      friend void  B* A::create(void);
   private:
     int x;
};

a.h

#include "b.h"

class A {
   public:
     void B* create(void);
   ...
};

basically class A creates "B" objects. I want to give the creation function create() access to modify the private member 'x' of class B. I want to simulate the 'internal' keyword in C#, but at a more granular level.

The problem I have is that I end up with a circular header reference. b.h wants to come after a.h, but a.h wants to come after b.h. What is the proper way of doing this? Do I need to resort to void* ptrs? Since I only create one type of object, i don't think I need the factory pattern. Hopefully I'm missing something simple.

+3  A: 

What you need is a "forward declaration". Basically you don't include the classes' headers in other classes' headers (unless you want to use composition, then you have to). In your case, it'd look like this:

// B.h
class A;
class B {
    // declare pointers to A freely
};

And the other way round in A.h.

You'd probably need to include A.h in B.cpp (and the other way round) to be able to actually dereference those pointers to access fields, but your problem with circular header inclusion is now gone.

Kos
Thanks. That worked; in my real code, I had an additional wrinkle that my classes were actually typedefs. If you forward declare the classes, you can then forward declare the typedefs.
Will I Am