For every pointer p1
of class class1
, are there any risks we should consider by using a forward declaration of class1
instead of including class1
header file?
I can see only the advantage: The header file will have less size.
The Google style guide recommends against using forward declarations, and for good reasons: If someone forward declares something from namespace std, then your code exhibits undefined behavior (but will likely work).
A forward declaration allows us to tell the compiler about the existence of an identifier before actually defining the identifier. In the case of functions, this allows us to tell the compiler about the existence of a function before we define the function's body.
In C++, Forward declarations are usually used for Classes. In this, the class is pre-defined before its use so that it can be called and used by other classes that are defined before this. Example: // Forward Declaration class A class A; // Definition of class A class A{ // Body };
As the name itself implies, forward declaration is just a Declaration and not a definition. So, you will declare saying the compiler that it is a class and I just declaring it here and will provide you the definition when am gonna use it. So, normally you forward declare in the Header file and #include in the .
I can see only the advantage: The header file will have less size.
That's not exactly the point.
Let's assume you have a class declaration in a header file like
namespace MyNamespace {
class Baz;
}
class Foo {
public:
void bar(const MyNamespace::Baz & x);
};
and the definition in a separate translation unit as
#include "Baz.hpp"
void Foo::bar(const MyNamespace::Baz & x) {
// actually do something with Baz
}
and in contrast having everything included in the header file (and necessarily all dependent sources will be recompiled when Baz.hpp
will be changed)
#include "Baz.hpp"
class Foo {
public:
void bar(const MyNamespace::Baz & x);
};
with the declaration, the 1st version might help to compile the code a little bit faster.
Especially if you have your own headers and class declarations, and if any of these are likely to be changed, you only want to recompile your translation units in the codebase, and not every source file that includes your type dependent header.
Note that forward declarations can be only used with references and pointers. Also header inlined code which dereferences to the forwarded type members cannot be used.
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