How can i prevent class redefinition problem ?
hi all,
suppose there are three files a.h,b.h,c.h
which contain classes a,b,c respectively.
and let c.h included in b.h and b.h included in a.h.
Code:
//c.h
class c
{ ....
};
//b.h
#include c.h
class c
{...
}
//a.h
#include b.h
#include c.h
class a
{...
}
On compiling there comes an error of class redeclaration ..... how can we prevent this ?
Re: How can i prevent class redefinition problem ?
ok putting the b.h file in #ifndef ... #endif block solved the problem ... :o
Re: How can i prevent class redefinition problem ?
Quote:
Originally Posted by ankurjain
hi all,
suppose there are three files a.h,b.h,c.h
which contain classes a,b,c respectively.
and let c.h included in b.h and b.h included in a.h.
Code:
//c.h
class c
{ ....
};
//b.h
#include c.h
class c
{...
}
//a.h
#include b.h
#include c.h
class a
{...
}
On compiling there comes an error of class redeclaration ..... how can we prevent this ?
The standard way is
Generic header file
Code:
#ifndef <FILENAME>_H
#define <FILENAME>_H
class <ClassName>
{
};
#endif // <FILENAME>_H
In example
Code:
// a.h
#ifndef a_h
#define a_h
class a
{
};
#endif // a_h
Code:
// b.h
#ifndef b_h
#define b_h
#include "a.h"
class b
{
};
#endif // b_h
Code:
// c.h
#ifndef c_h
#define c_h
#include "a.h"
#include "b.h"
class c
{
};
#endif // c_h
In this way the second inclusion of "a.h" are ignored by precompiler.
Re: How can i prevent class redefinition problem ?
If you use Visual C++, you can also try:
#pragma once
at the top of each header file, this makes the compiler read the header just once.
Re: How can i prevent class redefinition problem ?
Quote:
Originally Posted by gfunk
If you use Visual C++, you can also try:
#pragma once
at the top of each header file, this makes the compiler read the header just once.
Beware that this solution isn't portable.
Re: How can i prevent class redefinition problem ?
Put all Class declaration in One generic header file.
such as:
Code:
//className.h
#ifndef CLASS_NAME_H
#define CLASS_NAME_H
class a;
class b;
class c;
//....
#endif //CLASS_NAME_H