Search code examples
c++aggregationcompositionmodel-associationscross-reference

How to implement association in c++


I want to implement association I C++, but I am getting several errors and I am unable to solve them.

Class A{

public: //methods
private:
B * b_obj;

};

Class B{
public: //methods
private:
A * a_obj;
}

Both these classes are in separate files. i.e. A.h, A.cpp, B.h and B.cpp. VS2012 is giving errors Error C2061: syntax error near A


Solution

  • This particular cross-reference situation can be handled in multiple ways.

    Assuming that you can't just let A.h include B.h and B.h include A.h because, when including headers at most once, one will be included always before the other, the simplest solution is just to use forward references:

    A.h

    class B;
    
    class A {
      B* bObj;
    }
    

    A.cpp

    #include "A.h"
    #include "B.h"
    
    ...
    

    B.h

    class A;
    
    class B {
     A* aObjM;
    }
    

    B.cpp

    #include "B.h"
    #include "A.h"
    
    ...
    

    This simple solution doesn't allow you to use A specifications in B.h (eg calling a method) and vice-versa, nor it allows you to store concrete instances (A vs A*) in the B class but it doesn't sound like your case.