Why are redefinition errors?
Make sure your header files have the appropriate Header Guard / Include Guards . Most likely, you missed the addition of the title protects and, therefore, causes multiple class definitions due to the inclusion of the title several times.
Why is the forward declaration in order in this case?
When instead of including the header file, you add the line:
class doc;
It Forwards declares the doc
class, which means that for the compiler it is an Incomplete type . With incomplete types, you cannot create objects or do anything that is necessary for the compiler to know the doc
layout or more than the fact that doc
is just a type. ie: the compiler does not know what its members are and what its memory layout is.
But since pointers to all objects must have the same memory allocation, you can use the forward declaration by simply pointing to an incomplete type as a pointer.
In this case, the only way doc
refers to is to point to the doc
class, and therefore the Forward declaration will also work.
BottomLine:
Including the header file should work for you. If you have adequate intrusion protection in place. And there is nothing wrong with that. However, Forward declaring a class should also work for you due to the above reasoning. Please note that forward declarations are usually used if there is a circular dependency of classes.
What is better Include header File
or Forward Declaration
?
The inclusion of the just copied header file inserts the code from the header where the file was included, which can mainly result in:
- Increase compilation time
- Global namespace pollution.
- Potential collision of preprocessor names.
- Increase in binary size (in some cases, although not always)
The forward declaration has its own restrictions on how to use the incomplete type.
With an incomplete type, you can:
- Declare an element as a pointer or reference to an incomplete type.
- Declare functions or methods that accept / return incomplete types.
- Define functions or methods that accept / return pointers / references to an incomplete type (but do not use its elements).
With an incomplete type, you cannot:
- Use it as a base class.
- Use it to declare a member.
- Define functions or methods using this type.
Given the possibility (due to the above restrictions on the use of an incomplete type), you should prefer a forward declaration with the inclusion of a header.
source share