Search code examples
c++classpointersparent

C++: parent pointer to class that includes the child


I have a class design problem that could simplified with this example:

// foo.h
#include "foo2.h" 
class foo
{
public:
    foo2 *child;
// foo2 needs to be able to access the instance
// of foo it belongs to from anywhere inside the class
// possibly through a pointer
};

// foo2.h
// cannot include foo.h, that would cause an include loop

class foo2
{
public:
    foo *parent;
// How can I have a foo pointer if foo hasn't been pre-processed yet?
// I know I could use a generic LPVOID pointer and typecast later
// but isn't there a better way?
};

Is there any other way other than using a generic pointer or passing the parent pointer to every call of foo2 members?


Solution

  • You don't need to include the file if you're only using a pointer, and you won't have looping trouble if you include them in .cpp files:

    // foo.h
    class foo2; // forward declaration
    class foo
    {
    public:
        foo2 *child;
    };
    
    // foo2.h
    class foo;
    class foo2
    {
    public:
        foo *parent;
    };
    
    //foo.cpp
    #include "foo.h"
    #include "foo2.h"
    
    //foo2.cpp
    #include "foo2.h"
    #include "foo.h"
    

    Although you may be better off by rethinking your design.