By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
432,463 Members | 771 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 432,463 IT Pros & Developers. It's quick & easy.

bi-directional relationship include problems

P: 22
Helo everybody!

I need help with a error I get compiling the folowing code:
//File ClassA.h
#ifndef CLASSA_H
#define CLASSA_H
#include "ClassB.h"

class ClassA{
private:
ClassB *lnkAToB;
public:
ClassA(ClassB *lnk);
};
#endif
//File ClassA.cpp
#include "ClassA.h"

ClassA::ClassA(ClassB *lnk){
this->lnkAToB = lnk;
}


//File ClassB.h
#ifndef CLASSB_H
#define CLASSB_H
#include "ClassA.h"
class ClassB {
private:
ClassA *lnkBToA;
public:
ClassB(ClassA *lnk);
};
#endif
//File ClassB.cpp
#iclude "ClassB.h"

ClassB::ClassB(ClassA *lnk){
this->lnkBToA = lnk;
}

the error I get compiling is:
"ClassB.h": E2303 Type name expected at line 6
Sep 17 '06 #1
Share this Question
Share on Google+
2 Replies


Banfa
Expert Mod 5K+
P: 8,916
The problem you have is you have tried to inlcude ClassA.h into ClassB.h and ClassB.h into ClassA.h. This is impossible, 1 must be included before the other logically they can not both come first. In your case ClassB.h is the one that is included first followed by ClassA.h so the error is created in ClassB.h

This can be followed from the C file

C file includes ClassA.h
ClassA.h checks CLASSA_H it is not defined
ClassA.h defines CLASSA_H
ClassA.h includes ClassB.h
ClassB.h checks CLASSB_H it is not defined
ClassB.h defines CLASSB_H
ClassB.h includes ClassA.h
ClassA.h checks CLASSA_H it is defined, all code in ClassA.h is excluded
ClassB.h defines it's code, this code is dependent on class ClassA which the compiler has not see yet and an error is produced


There is an easy solution to this, you can forward declare the class, that is tell the compiler that there is going to be a class called ClassA without actually defining it. This works because class by only uses references to ClassA not any actual members for it so the compiler has all the information it requires to set-up ClassB (the fact that there will be a pointer to class in it).

If you do this then ClassB.h will look like

Expand|Select|Wrap|Line Numbers
  1. //File ClassB.h
  2. #ifndef CLASSB_H
  3. #define CLASSB_H
  4.  
  5. class ClassA;
  6.  
  7. class ClassB {
  8. private:
  9.   ClassA *lnkBToA;
  10.  
  11. public:
  12.   ClassB(ClassA *lnk);
  13. };
  14. #endif
  15.  
If the code of ClassB uses members of A through the pointer that is fine because you can include ClassA.h into ClassB.cpp, this just removes the dependency of the header files on each other.

You could also do the same thing for ClassA.h
Sep 17 '06 #2

P: 22
Thank you very much you saved my live!!!
Very nice explanation!
Sep 17 '06 #3

Post your reply

Sign in to post your reply or Sign up for a free account.