Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the risks to massively forward declaration classes in header files?

Tags:

c++

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.

like image 878
Stav Alfi Avatar asked Dec 13 '17 20:12

Stav Alfi


People also ask

Are forward declarations good?

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).

Why should I use forward declarations?

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.

What is forward declaration of a class when and why is it needed?

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 };

Should I use forward declaration or include?

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 .


1 Answers

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.

like image 72
user0042 Avatar answered Oct 01 '22 18:10

user0042