Viku
Viku

Reputation: 2973

Error in including header file

Hi i have two classes A and B . in A i am using the header file for B so that i can create an instance for B( e.g. B *b ) and the something i am doing in Class B also i.e including the header file of A and creating the instance for A(e.g. A *a) in B .

while i am including the header file for A in B it gives me the following error in A.h

1>c:\Bibek\A.h(150) : error C2143: syntax error : missing ';' before '*'
1>c:\Bibek\A.h(150)(150) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\Bibek\A.h(150)(150) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

Upvotes: 1

Views: 5263

Answers (1)

Attila
Attila

Reputation: 28782

It sounds like you are including the header files in a circular manner (A.h includes B.h, which includes A.h). Using header guards means that when B.h includes A.h in the above scenario, it skips that (due to the now active include guard of A.h), so the types in A.h are not yet defined when parsing B.h.

To fix, you can use forward declarations:

// A.h
#ifndef A_H
#define A_H

// no #include "B.h"

class B; // forward declaration of B
class A {
  B* b;
};

#endif

similarly for B.h

This allows you to use pointers of the forward declared class (e.g. in declarations of member variables, member function declarations), but not use it in any other way in the header.

Then in A.cpp you need to have the proper definition of B.h, so you include it:

// A.cpp

#include "A.h"
#include "B.h" // get the proper definition of B

// external definitions of A's member functions

This construction avoids the circular inclusion of the header files while allowing full use of the types (in the .cpp files).

Note: the error about the non-support of default int happens as the compiler does not have the proper definition of A when including B.h, (the C language allows default int definition for unknown types, but this is not allowed in C++)

Upvotes: 4

Related Questions