Circular headerfile inclusion problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • xoinki
    New Member
    • Apr 2007
    • 110

    Circular headerfile inclusion problem

    hi all,

    I have 3 classes. class A, class B, and class C, class D, defined in 4 files A.cpp, B.cpp, C.cpp, D.cpp
    inheritence hierarchy is as follows.
    A--> B --> C
    |
    |
    V
    D
    i.e, A is inherited by B which is inherited by C and D.
    then, A and B has a virtual function test() overridden in C and D.
    and I need to use dynamic binding as follows..
    Code:
    //this would be a member function of A
    bool A::SomeFunc()
    {
    A * var;
    if(some condition)
        var = new C();
    else
        var = new D();
    ..
    ..
    ..
    return TRUE;
    }
    so problem is..
    A needs C and D.
    C and D needs B.
    and B needs A.
    so there is a circular inclusion.
    becuase of which base classes inherited are not recognised.
    can anybody suggest a solution? is this a common problem?

    waiting for your reply,
    Xoinki
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    This should not be a problem as long as bool A::SomeFunc() is defined in a CPP file and not a header file.

    It is just a matter of including the headers in the right order at the top of the A.CPP file, probably

    [code=cpp]
    #include "A.h"
    #include "B.h"
    #include "C.h"
    #include "D.h"
    [/code]

    This is more of a problem if there are 2 classes X and Y each of which has methods that take a pointer or reference to the other class. In this case you need to know and X in Y.H and Y in X.H which does create a header file interdependency .

    The way round this is a forward declaration, this looks something like
    [code=cpp]
    class X;
    [/code]This tells the compiler "at some point in the future I am going to declare a class named X" and provides the compiler with enough information to create pointers and references to the class (but not to access the class members).

    Comment

    Working...