Consider this:
#ifndef A_H
#define A_H
#include "b.h"
class A
{
B* b;
};
#endif
#ifndef B_H
#define B_H
#include "a.h"
class B
{
A* a;
};
#endif
Now you try to turn on one of the files in the other, say #include "a.h".
The compiler will analyze it as:
#ifndef A_H
#define A_H
fine - A_Hnot defined
#include "b.h"
try pasting the contents:
#ifndef B_H
#define B_H
ok since B_Hnot defined
#include "a.h"
it will not determine A, because it is A_Hdetermined. So we have
class B
{
A* a;
};
which will result in an error because it has Anot been defined or not declared before use.
The forward declaration corrects this.
Of course, the best solution for this is to not include it at all (unless you need to).
source
share