mgiuffrida mgiuffrida - 2 months ago 8
C++ Question

Does a C++ function that returns, but doesn't use, a type need to #include that type?

Does this file required an

#include
to define
FooType
? The function's type signature returns
FooType*
but the function implementation doesn't use
FooType
.

// test.cpp
class FooType; // Unresolved forward declaration

FooType* GetFoo() { return nullptr; }


It builds without warnings using
g++ --std=c++11 -Wall
. So is this a legal use of forward declaration?

Answer

From the cppreference:

A declaration of the following form

class-key attr identifier ;

Declares a class type which will be defined later in this scope. Until the definition appears, this class name has incomplete type.

...

and if a particular source file only uses pointers and references to the class, this makes it possible to reduce #include dependencies.

So this syntax is perfectly valid, because you use a pointer Foo*.