Class name does not name a type in C++

Viewed 188056

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 _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

File A.cpp:

#include "A.h"
#include "B.h"
#include <cstdio>

A::A(int id): _id(id), _b(){
    printf("hello\n the id is: %d\n", _id);
}

File B.h:

#ifndef _B_h
#define _B_h

class B{
    public:
        B();
};
#endif

File B.cpp:

#include "B.h"
#include <cstdio>

B::B(){
    printf("this is hello from B\n");
}

I first compile the B class and then the A class, but then I get the error message:

A.h:9: error: ‘B’ does not name a type

How do I fix this problem?

12 Answers

NOTE: Because people searching with the same keyword will land on this page, I am adding this answer which is not the cause for this compiler error in the above mentioned case.

I was facing this error when I had an enum declared in some file which had one of the elements having the same symbol as my class name.

e.g. if I declare an enum = {A, B, C} in some file which is included in another file where I declare an object of class A.

This was throwing the same compiler error message mentioning that Class A does not name a type. There was no circular dependency in my case.

So, be careful while naming classes and declaring enums (which might be visible, imported and used externally in other files) in C++.

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.

Try to move all includes outside namespace.

//Error
namespace U2 {

#include <Head.h>
#include <LifeDiode.h>

}

//Solution

#include <Head.h>
#include <LifeDiode.h>

namespace U2 {

}

Not the answer, but for me the thing was that I forgot to add the std:: before the potential type to properly use it.

It actually happend to me because I mistakenly named the source file "something.c" instead of "something.cpp". I hope this helps someone who has the same error.

Related