I know you can do something like:
def.h:
A();
int x;
A.h
class A
{
public:
#include "def.h"
}
A.cpp
A::A()
{
x = 0;
}
int main()
{
A a;
return 0;
}
My questions is: why would you do this? Are there any advantages? I can see how it would be helpful if you have some classes with the same members but not the same base, but is it worth the hassle? It’s not very readable, is it?
Also, how does the compiler treat these includes? Does it just paste the content of the header where it’s included (kind of like a macro)?
The preprocessor (which runs before anything), when it stumbles upon an
include, almost literally copies the content of that header and pastes it in the place of the#includedirective.The advantages of using it like you describe are few, the main one being that you don’t have to duplicate code.
However, in 9999/10000 situations, it is definitely not worth the hassle. If you have a typo somewhere in the header file, you’ll get strange errors in every file that uses it, and it’s not clear at all what it’s doing until you actually open the file and read it.
Avoid that if at all possible. I can’t think of a situation where it would be absolutely necessary; the same effect can be achieved with inheritance or composition most of the time without all the side-effects.