C++ Error C2011 - What it is and how to fix it

Errors are never fun to deal with, especially late at night with no one around to bounce ideas off of. During the course of my programming adventures I encounter many errors in compilation and hopefully, by posting them and the solution for them I might help myself later, or others, in solving the problem.

Error C2011 - 'ClassName' : 'class' type redefinition

C++ Error C2011

C++ Error C2011

What is it? Error C2011 highlights that you are trying to redefine code which has previously been defined.
Common causes Common causes include circular referencing and including a header file more than once (see example below).
How to fix it? You can fix this error by ensuring that the class you are including does not get included more than once. Two ways to do this - the first is to go through your code and only include header files if necessary to that class (see this post for the difference between inclusion and inheritance - maybe you want to inherit instead?). The second is to protect the class causing the error (i.e. the one being included) from being included more than once. See examples below for how to do this.

Example cause

An example cause of this error comes from including a header file more than once when trying to compile your code. For example, if you have three classes, Foo, Bar, and Boo, with Foo being an include file for both Bar and Boo, and Boo including Bar as well, we might have code which looks like this:

When we come to compile this code and boo is compiled, the compiler will see that it needs to compile bar first (to make sure bar is fit for inclusion). While compiling bar, the compiler sees that foo needs compiling (to make sure foo is fit for inclusion). Following the successful compilation of foo, bar will compile and the compiler returns to boo. It then see's that it needs to compile foo (to make sure foo is fit for inclusion) into boo, however, this is where C2011 will occur - foo has already been compiled and thus, has already been defined.

Example fixes

There are two ways to fix the error described above. The first is to reformat the inclusions so that foo is only included once, or consider inheritance over inclusion (if that works - don't inherit unnecessarily of course).

The second is to define something uniquely within the class so that if the compiler comes back to the class to re-compile it knows not to bother compiling it again. This is done using #ifndef, #define and #endif, as seen in the example below.

Obviously, good programming practice suggests you try to use the first option and ensure the file isn't being included twice unnecessarily, but if you're in a pinch, this will solve your problem.

Leave a Reply

Your email address will not be published. Required fields are marked *