#include trouble

Started by
3 comments, last by WuTz 14 years ago
Hi. I got a situation where I need to uhm.. cross-include (Or so :P) One header includes the other one (Over some wired paths). And the compiler tells me always: "missing ; before *" when I declare MyClass* Something; Can I use a forward deceleration to fix this? I have to be able to call functions from that class...
Advertisement
Sure, go for it.
Nice, thanks! I tried and it wasn't working. But then I tried harder and now everything is good. :)
Header files can be troublesome. I have found a nice resource which explained the best practice but lost the URL.

So let me try to explain it.
The best way is always to use forward declaration where possible and only
use include when necessary.

Let us look at an example:
class MyClass : public BaseClass {public:  Entity* getEntity();};


Here you need to include BaseClass. The compiler and preprocessor needs to know the size and so on of your BaseClass. But for the Entity just use forward declaration. It is only a pointer so a forward declaration is perfectly fine. Include the actual header file in your cpp file.
So the example looks like
#include "BaseClass.h"class Entity;class MyClass : public BaseClass {public:  Entity* getEntity();};


This works nice and can help you especially when you have these cyclic dependencies.

This is how I learned it and it works fine for me.

If I am wrong hopefully someone will explain it.
I did it exactly like this, but I had to do some more forward decelerations. Now it works :)

This topic is closed to new replies.

Advertisement