Circular includes and forward declarations
Hi, so I'm having a bit of an issue, and I know it has to do with the fact that I have circular includes, but it seems somewhat necessary. Here's essentially what I have:
Code:
// Base.h
#pragma once
#include "SpecificChild.h"
class Base {
SpecificChild* mySpecificChild;
};
Code:
// SpecificChild.h
#pragma once
#include "Base.h"
class SpecificChild : public Base {
};
The issue is that when Base.cpp gets compiled, it includes Base.h. Base.h in turn includes SpecificChild.h. SpecificChild.h tries to include Base.h but sees nothing because of the #pragma once (essentially an #ifdef _BASE_H ... #endif for those not familiar with MSVC). I have had this issue before when I was dealing with two different, unrelated classes, and that was fixed by putting a simple forward declaration in each header file. However, putting "class Base;" above SpecificChild's declaration (and putting "class SpecificChild;" above Base's declaration just in case), still does not help. I get the following error:
"'Base' : base class undefined"
Obviously, and easy and cheap solution to this would be just to change the reference to SpecificChild in Base to just a Base, but I would like to use stuff specific to SpecificChild, and it seems pointless to cast it every time I want to do so.
Is there some specific way of forwardly declaring a class that you intend to use as a base? Thanks.
Re: Circular includes and forward declarations
The problem is not the includes but the logic of your class struction.
SpecificChild is derived from Base, so a SpecificChild object is also a Base object.
Now a Base object includes a SpecificChild object, which means each Base object includes a Base object which includes a Base object which includes ....
How would such an object look like? Infinitely large? Or infinitely small as it does not contain anything other than infinitely small objects?
PS: Congratulations!!! First post and correct usage of code tags ! Haven't seen that for quite some time.
Re: Circular includes and forward declarations
Ok, well I didn't actually compile the thing given, it's really a pointer. I'll fix it in the original post. That fixes the whole issue with a Base being in a Base (which of course is a huge issue).
Re: Circular includes and forward declarations
So now you can replace your include
Code:
#include "SpecificChild.h"
with a forward declaration
Code:
class SpecificChild;
Problem solved.
Re: Circular includes and forward declarations
Alright that seems to work, thank you!