Possible Duplicate:
C header file loops
Original Question:
I always had problems understanding why the following gives errors:
something.h
#ifndef SOMETHING_H
#define SOMETHING_H
#include "somethingelse.h"
#endif
somethingelse.h
#ifndef SOMETHINGELSE_H
#define SOMETHINGELSE_H
#include "something.h"
#endif
Why does this give errors?
1) SOMETHING_H is not defined
2) SOMETHING_H becomes defined, somethingelse.h get included
3) SOMETHINGELSE_H is not defined, becomes defined, and something.h gets included
4) SOMETHING_H is defined, jump to #endif, this should be the end of it?
EDIT:
turns out it doesn't give any errors at all. However the following does:
something.h
#pragma once
#include "somethingelse.h"
class something {
int y;
somethingelse b;
};
somethingelse.h
#pragma once
#include "something.h"
class somethingelse {
something b;
int x;
};
And it is logical, because the class 'something' is not yet defined when 'somethingelse' needs an instance of that class.
The problem is solved by forward definition:
something.h
#pragma once
class somethingelse;
class something {
int y;
somethingelse* pB; //note the pointer. Correct me if I'm wrong but I think it cannot be an object because the class is only declared, not defined.
};
in the .cpp, you can include "somethingelse.h", and make instances of the class.