As an optimisation, or to avoid include looping, a type may be forward declared, This leads to code like:
class A;
class B
{
A *a;
};
If the number of forward declaration becomes large, it can take up a lot of space at the top of the header file. Is there a way of forward declaring and using at the same time? Sort of like:
class B
{
extern A *a;
};
I've never really thought about this before, but I have a header with a bunch of forward declarations and I would like to make it tidier (without farming them off to another include file).
EDIT: I changed 'a' to a pointer, as it was rightly pointed out that you can only use forward declare on pointers and references.
What you're asking isn't completely clear but, if I understand you right, you can forward declare at the same time as declaring your variables:
class B
{
class A* a; // declaring A as class is an in-place forward declaration
};
Is that what you mean?
A forward declaration wouldn't allow you to do
class A;
class B
{
A a;
};
unless A
is a reference or pointer type, since a forward declaration doesn't give any additional information on the size of the object (unless for enum class
in C++11). So are you using pointers/references? Otherwise it means you are including the definition of A
for sure.
Regarding your problem there is no way to forward declare and use a type since we're talking about two different things. A variable declaration doesn't define a type, it defines a variable.
A simple solution to your problem would be to gather all forward declaration in a single header file and include it in the project (or in your eventual precompiled header). This wouldn't create too much problems, since forward declarations don't expose anything nor they are heavyweight.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With