skip to content

In a C++ header, when can you forward-declare a class instead of including its header, and when must you include it?

level: middleimportance: should knowfreq 58%

answer

  1. incomplete type
  2. pointers and references are fine
  3. size and members need the definition
  4. by-value member, base class, sizeof
  5. never forward-declare std types

basics

~20 s

A forward declaration such as class Lidar; makes Lidar an incomplete type: enough for pointers, references and function declarations. Anything needing its size or members, such as a by-value member, a base class, sizeof or a member call, needs the definition.

solid answer

~50 s

`class Lidar;` declares the name and leaves `Lidar` an **incomplete type**. That is enough to declare `Lidar*` and `Lidar&` members and parameters, and to *declare* functions that take or return `Lidar` by value. The full definition is needed wherever the compiler must know the size or the members: a data member of type `Lidar`, a base class, `sizeof`, `new Lidar`, a member access, or defining or calling a function that passes `Lidar` by value. So a header forward-declares what it only points at and includes what it embeds or derives from, and the `.cpp` file includes the real header. Each forward declaration removes a dependency: editing `lidar.h` no longer recompiles every includer of `robot.h`. Do not forward-declare standard library names yourself: adding declarations to namespace `std` is undefined behaviour, and `<iosfwd>` exists for the stream types.

code

cpp · 24 lines
cpp
#include <cstdio>

class Lidar;                       // forward declaration: Lidar is incomplete here

class Robot {                      // what robot.h needs to say about Lidar
public:
    explicit Robot(Lidar& l) : lidar_(&l) {}
    double range() const;          // declared only: its body needs Lidar complete
private:
    Lidar* lidar_;                 // a pointer to an incomplete type is fine
};

class Lidar {                      // the full definition (lidar.h in a real project)
public:
    double last_range = 4.2;
};

double Robot::range() const { return lidar_->last_range; }  // robot.cpp

int main() {
    Lidar l;
    Robot r(l);
    std::printf("%.1f\n", r.range());
}

go deeper

for a junior

Recall that class Lidar; lets you use Lidar pointers and references but not a Lidar member by value, and that the .cpp file still includes the real header.

for a middle

Explain the incomplete-type rule: anything needing size or members needs the definition. List the cases, including a base class, sizeof, an inline body and calling a by-value function.

for a senior

Use forward declarations as a build-dependency tool: show which include they remove from which rebuild, and know the traps, such as std names, opaque enums and inline bodies that dereference.

for a principal

Set the team rule: headers include only what they embed or derive from and forward-declare the rest, with a checker to enforce it, weighing the minor cost against incremental build time.

## Complete and incomplete types After `class Lidar;` the compiler knows that `Lidar` names a class and nothing else: not its size, not its members, not its base classes. The standard calls such a class an **incomplete type**. It becomes complete when its definition, `class Lidar { ... };`, is reachable. The rule that decides every case: a use that needs the **size** or the **members** of `Lidar` requires the complete type, and any other use works with the incomplete one. ## What an incomplete type allows - **Pointers and references**: `Lidar* lidar_;` as a member, `void attach(Lidar& l);` as a parameter. A pointer's size does not depend on what it points to. - **Function declarations** that take or return `Lidar` **by value**: `Lidar make_lidar();` compiles. Only *defining* or *calling* such a function needs the full type. - **Friend declarations** and further declarations of the same name. - **`std::unique_ptr<Lidar>` as a member**: the standard lets `unique_ptr`'s `T` be incomplete, but the deleter requires `T` complete wherever the pointer is destroyed, which is why a pimpl class declares its destructor in the header and defines it in the `.cpp`. - **Standard containers**: the standard allows `std::vector`, `std::list` and `std::forward_list` to be *instantiated* with an incomplete element type, provided it is complete before any member of the container is used. ## What needs the full definition The standard lists the contexts in which a class type must be complete. The ones a header meets most often are: 1. a non-static data member **of type** `Lidar` 2. `Lidar` as a **base class** 3. `sizeof(Lidar)`, `alignof(Lidar)`, or `new Lidar` 4. a **member access** such as `lidar->range()` 5. **defining or calling** a function with a `Lidar` parameter or return type passed by value 6. an inline member function body in the header that does any of the above Get one wrong and clang says so directly: ```plaintext a.cpp:3:12: error: field has incomplete type 'Lidar' a.cpp:1:7: note: forward declaration of 'Lidar' ``` | In `robot.h` | `class Lidar;` enough? | |---|---| | `Lidar* lidar_;` | yes | | `void attach(Lidar& l);` | yes | | `Lidar scan_once();` (declaration only) | yes | | `Lidar sensor_;` | no, needs the size | | `class Robot : public Lidar` | no, needs the layout | | `double range() const { return lidar_->range(); }` inline | no, needs the members | ## Why it matters: the dependency you remove Every `#include` in a header becomes an include in each file that includes that header, transitively. If `robot.h` includes `lidar.h`, then editing `lidar.h` recompiles every file that includes `robot.h`, even files that never touch a `Lidar`. Replacing the include with `class Lidar;`, and moving the include into `robot.cpp`, cuts that edge: `lidar.h` changes now recompile only the files that really use `Lidar`. In a large codebase, this one habit decides a large share of incremental build time. ## Enumerations and the standard library - **Enumerations** can be forward-declared with an **opaque enum declaration**: `enum class Mode;` or `enum class Mode : std::uint8_t;`. An unscoped enumeration may be declared this way only with a fixed underlying type, `enum Gear : int;`. Plain `enum Gear;` is ill-formed, and clang says `ISO C++ forbids forward references to 'enum' types`. - **Standard library names** are off limits. The standard makes it undefined behaviour to add declarations to namespace `std`, and many names are not what they look like: `std::string` is an alias for `std::basic_string<char>`, so `namespace std { class string; }` collides with the real declaration. For the stream types the library ships `<iosfwd>`, a header of exactly the forward declarations you would want. ## The cost side Forward declarations are not free of trade-offs: - An inline function body that dereferences the pointer must move to the `.cpp` file, which can cost a little run-time inlining unless link-time optimisation recovers it. - A forward declaration duplicates a fact; if the class is renamed, moved to another namespace or turned into an alias, every forward declaration must change too, and the compiler reports the mismatch only where both declarations meet. - A class template with default template arguments is awkward to forward-declare by hand; that is what dedicated forwarding headers are for.

  • Why does Lidar make_lidar(); compile with only class Lidar; in scope?
    Declaring a function does not need the size of its parameter or return types, so an incomplete `Lidar` is fine there. The complete type is needed only where the function is defined or called, because that is where the compiler must build, copy or destroy a `Lidar` object. Headers rely on this to declare factories without including the class's header.
  • How do you forward-declare an enumeration in a header?
    With an opaque enum declaration: `enum class Mode;`, or with an explicit underlying type, `enum class Mode : std::uint8_t;`. An unscoped enumeration needs the fixed underlying type, as in `enum Gear : int;`; plain `enum Gear;` is ill-formed because the compiler cannot know its size. Every later declaration and the definition must use the same underlying type.

  • A forward declaration lets you hold the class by value as a member.
  • You may forward-declare std::string yourself to avoid including <string>.
  • Forward declarations only speed things up for pointer-heavy code.
  • A function returning the class by value always needs its full definition.
  • Any enum can be forward-declared with enum Name;.