So, thanks to this website, I found the answer to my previous problem. I\'m adding a function to a class in a GNU automake project that uses a pointer to a doc
Why the Redefinition errors?
Please ensure that your header files have appropriate Header Guards/Include Guards.It is most likely that you have missed adding header guards and hence that causes multiple class definitions due to the header getting included multiple times.
Why Forward Declaration is okay in this case?
When instead of including the header file you add the line:
class doc;
It Forward declares the class doc
which means for compiler it is an Incomplete type. With Incomplete types, One cannot create objects of it or do anything which needs the compiler to know the layout of doc
or more than the fact that doc
is just an type.
i.e: The compiler does not know what are its members and what its memory layout is.
But Since pointers to all objects need just the same memory allocation, You can use the forward declaration when just reffering to an Incomplete type as a pointer.
In this case the only way in which doc
is being referenced is an pointer to the class doc
and hence the Forward declaration will work as well.
BottomLine:
Including the header file should work for you If you have proper Inclusion Guards in-place.
And there is nothing wrong with it.
However, Forward declaring the class should also work for you because of the reasoning given above.Note that forward declarations are usually used in case where there is a Circular Dependency of classes.
Which is better Include header File
or Forward Declaration
?
Including the header file just copy pastes the code from the header to wherever the file was included, which basically could lead to:
Forward Declaration has its own limitations on how the Incomplete type can be used further on.
With Incomplete type you can:
With Incomplete type you cannot:
Given the possibility(due to above limitations on Incomplete type usage) One should prefer Forward Declaration over Including Header.