Forward announce and use in one step

As optimization, or to avoid including a loop, the type can be declared forward, this leads to the following code:

class A; class B { A *a; }; 

If the number of forward ads becomes large, it can take up a lot of space at the top of the header file. Is there a way to move forward and use at the same time? Example:

 class B { extern A *a; }; 

I have never thought about this before, but I have a header with a bunch of forward declarations, and I would like to make it more accurate (without a farm in another include file).

EDIT: I changed "a" to a pointer, as it was correctly pointed out that you can only use forward declare for pointers and references.

+6
source share
3 answers

What you are asking is not entirely clear, but if I understand correctly, you can forward the declaration at the same time as the declaration of the variables:

 class B { class A* a; // declaring A as class is an in-place forward declaration }; 

Is that what you mean?

+5
source

Forward declaration will not let you do

 class A; class B { A a; }; 

if A not a reference or pointer type, since the direct declaration does not contain additional information about the size of the object (if only for the enum class in C ++ 11). So do you use pointers / links? Otherwise, this means that you are defining the definition of A exactly.

Regarding your problem, there is no way to forward the declaration and use the type, as we are talking about two different things. A variable declaration does not define a type; it defines a variable.

A simple solution to your problem is to collect the entire declaration forward in one header file and include it in the project (or in your final precompiled header). This would not create too many problems, since forward declarations show nothing and do not have a heavy weight.

+4
source

No, you cannot do what you want. This answer about forward declarations should provide you with all the details, but in the summary you need a full definition of the type if you want to use it (including more or less does); and not just the fact that it exists (as stated more or less openly).

+3
source

All Articles