c++includecyclic-reference

Avoid cyclic references caused by C++ includes headers


I have 3 classes: A, B and C. C is #includeed by B, and B is #included by A. In class C i have defined a handler for a button, and when the button is pushed, C will PostMessage to object A. If i include A in C, i will have a cyclic reference, so what should i do to avoid this cyclic reference?

EDIT: All includes are made in implementation files.


Solution

  • You should use forward declarations. Since C is not the owner of A, I'll assume you have a pointer as a member. So you don't need to include:

    class A; //forward declaration
    class C
    {
        A* a;
    };
    

    In the implementation file, you'll include A.h but that's OK. Also, if you can, use forward declarations in A.h and B.h where possible.