Mar 17, 2011

C++ Error: Class does not name a type

What the compiler actually said:

MyClass does not name a type.

What the compiler was too polite to say:

You idiot, you forgot to specify the namespace. This message can be perplexing at first because you can see either the #include or forward declaration for your class and you know you've spelled it correctly but the message persistently says MyClass does not name a type. For example,  if MyClass is defined in MyNamespace and used as follows:
#include <MyLibrary/MyClass.h>

MyClass GetMyClass();
void SetMyClass (const MyClass& theClass);

Making the Compiler Happy

The Wrong Way

The error will be produced for both uses of MyClass. You can solve the problem by adding
     using namespace MyNamespace;
at the top of the file, but this is considered bad form as any code that includes this .h will now be bringing all of MyNamespace into scope.

If you find this article helpful check out my Pluralsight courses Eclipse Guided Tour – Part 1   and Eclipse Guided Tour – Part 2

A Better Way

using MyNamespace::MyClass;

You have the same issue, but now only  MyClass is in scope for any file that includes your header. Still that's significantly better than bringing in all the names in the namespace. 

The Best Way (most of the time)

The best approach in most cases is to just explicitly qualify the namespace for each use.
MyNamespace::MyClass GetMyClass();
void SetMyClass (const MyNamespace::MyClass& theClass);
In addition, if you use Eclipse's content assist you can avoid this problem altogether. Type MyCl ctrl space you won't get the match you were expecting. If you type MyNamespace::MyCl ctrl space you will. In practice I never type out my entire namespace either. If I want the  SyncorTouchScreen::NumericUpDown class, I would type syn ctrl-space (content assist isn't case sensitive) then arrow down and hit enter on SyncorTouchScreen, followed by num ctrl-space enter to select the NumericUpDown class. I will admit if I have a short classname or typedef (like say byte) in a long namespace name (like SyncorLibrary) that is used a lot. I'll just use the better way, instead of the best way because I feel it improves overall readability and ends up making the code easier to maintain. Although of late I've been using the ability to create namespace aliases. So I'll use
namespace SL = SyncorLibrary;
SL::byte looks a lot less cluttered, and by using a lighter gray for my namespace, names they’re still legible and not as intrusive.

About Me

My photo
Tod Gentille (@todgentille) is now a Curriculum Director for Pluralsight. He's been programming professionally since well before you were born and was a software consultant for most of his career. He's also a father, husband, drummer, and windsurfer. He wants to be a guitar player but he just hasn't got the chops for it.