. Advertisement .
..3..
. Advertisement .
..4..
I am working on cpp, but I found the following warning message:
A.h:9: error: ‘B’ does not name a type
Is there any way to stabilize the issue “class name does not name a type c++”? I read a lot of topics about this, but all of them were trying to install anything. Is this the correct way, or any recommendation for me? Please find the beginning command below:
#ifndef _A_h
#define _A_h
class A{
public:
A(int id);
private:
int _id;
B _b; // HERE I GET A COMPILATION ERROR: B does not name a type
};
#endif
#include "A.h"
#include "B.h"
#include <cstdio>
A::A(int id): _id(id), _b(){
printf("hello\n the id is: %d\n", _id);
}
#ifndef _B_h
#define _B_h
class B{
public:
B();
};
#endif
#include "B.h"
#include <cstdio>
B::B(){
printf("this is hello from B\n");
}
The cause: I think this error happens because the contents of the files
A.h
andB.h
are pasted into the include statement by the preprocessor. When the compiler parsesA.cpp
, the declaration of classA
will be found before it knows about classB
.The solution: There are two options for dealing with this:
B.h
inA.h
. Header files should be included in the files where they are required. You and others will be confused as the project expands if you rely on indirect inclusion through another header or a special order of includes in the compilation unit (cpp-file).A
, if a member variable of typeB
is used in classA
, the compiler has to know the exact and complete definition ofB
. Nevertheless, a forward declaration would work if you were using a pointer or reference toB
, because the memory the compiler has to reserve for a pointer or reference is independent of the class definition. This is how it would look:This will help avoid circular header dependencies.
In case anyone does the same stupid thing as me, here’s a tip: When I was trying to create a test program, I used Class rather than Class (with small C). I didn’t pay attention to the errors message and was unable to understand my problem for a long time.
So, my search for a solution led me to this place.