Class name does not name a type in C++

Class name does not name a type in C++

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:

  1. Include 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.
  2. 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 {
        A(int id);
        int _id;
        B & _b;

    This is very useful to avoid circular dependencies among headers.

I hope this helps.

error Class does not name a type

Just in case someone does the same idiotic thing I did …
I was creating a small test program from scratch and I typed Class instead of class (with a small C). I didnt take any notice of the quotes in the error message and spent a little too long not understanding my problem.

My search for a solution brought me here so I guess the same could happen to someone else.

Class name does not name a type in C++

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++.

Leave a Reply

Your email address will not be published.