A class being redefined

If you happen to be getting a redefinition error when compiling a code in C++, here’s the solution.


If you happen to be getting a redefinition error on a class when you
compile, you have to add these two lines at the top, before the code:

#ifndef CLASS_H
#define CLASS_H

Replace CLASS with the actual name of the class, it must be all in
caps, so for example if your class is called “number” then you would
write it “NUMBER_H”. At the end of the code add a line that says:

#endif

A redefinition error occurs when the header of a class is included twice, for example when you have a class like this one:

#include <stdio>
class A{
public:
A();
~A();
};

And then, for example, you have other two child classes like:

#include <stdio>
#include “A.h”
class B:public A{
public:
B();
~B();
};

and

#include <stdio>
#include “A.h”
class C:public A{
public:
C();
~C();
};

when you include the child classes into another class, such as:

#include <stdio>
#include “B.h”
#include “C.h”

That would generate an error when you try to compile, since class A is
being defined twice, once when B.h is defined and once when C.h is
defined. So to prevent this you would simply add the lines of code
mentioned above, so the code would look like:

#ifndef A_H
#define A_H
#include <stdio>
class A{
public:
A();
~A();
};
#endif

So the class A would only get defined once not twice or more times. Also remember that this goes only in the header files (.h).

And always remember to leave one blank line at the end.

-LM

0 Responses to “A class being redefined”


  1. No Comments

Leave a Reply