I just started programming in C++, and I\'ve tried to create 2 classes where one will contain the other.
File A.h
:
#ifndef _A_h
#define
when you define the class A, in A.h, you explicitely say that the class has a member B.
You MUST include "B.h" in "A.h"
The preprocessor inserts the contents of the files A.h
and B.h
exactly where the include
statement occurs (this is really just copy/paste). When the compiler then parses A.cpp
, it finds the declaration of class A
before it knows about class B
. This causes the error you see. There are two ways to solve this:
B.h
in A.h
. It is generally a good idea to include header files in the files where they are needed. If you rely on indirect inclusion though another header, or a special order of includes in the compilation unit (cpp-file), this will only confuse you and others as the project gets bigger.If you use member variable of type B
in class A
, the compiler needs to know the exact and complete declaration of B
, because it needs to create the memory-layout for A
. If, on the other hand, you were using a pointer or reference to B
, then a forward declaration would suffice, because the memory the compiler needs to reserve for a pointer or reference is independent of the class definition. This would look like this:
class B; // forward declaration
class A {
public:
A(int id);
private:
int _id;
B & _b;
};
This is very useful to avoid circular dependencies among headers.
I hope this helps.
The solution to my problem today was slightly different that the other answers here.
In my case, the problem was caused by a missing close bracket (}
) at the end of one of the header files in the include chain.
Essentially, what was happening was that A
was including B
. Because B
was missing a }
somewhere in the file, the definitions in B
were not correctly found in A
.
At first I thought I have circular dependency and added the forward declaration B
. But then it started complaining about the fact that something in B
was an incomplete type. That's how I thought of double checking the files for syntax errors.
Aren't you missing the #include "B.h" in A.h?