mgiuffrida mgiuffrida - 1 year ago 60
C++ Question

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

Does this file required an

to define
? The function's type signature returns
but the function implementation doesn't use

// 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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download