C++ Logo


Advanced search

Idea: extend forward declarations to include base class(s)

From: John Yates <john_at_[hidden]>
Date: Fri, 21 Feb 2020 12:53:34 -0500
This is just a kernel of an idea. It addresses a problem on which I have
"subbed my toe" many, many times, namely that forward declarations do not
express the inheritance hierarchy. This issue is significant enough that
the Google C++ style guide advices against using forward declarations:

> - Forward declarations can save compile time, as #includes force the
> compiler to open more files and process more input.
> - Forward declarations can save on unnecessary recompilation.
> #includes can force your code to be recompiled more often, due to unrelated
> changes in the header.
> *Cons:*
> - ...
> - It can be difficult to determine whether a forward declaration or a
> full #include is needed. Replacing an #include with a forward declaration
> can silently change the meaning of code:
> * // b.h:*
> * struct B {};*
> * struct D : B {};*
> * // good_user.cc:*
> * #include "b.h"*
> * void f(B*);*
> * void f(void*);** void test(D* x) { f(x); } // calls
> f(B*)*

          If the #include was replaced with forward decls for B and D,
> test() would call f(void*).

The cited problem would disappear if struct D's forward declaration were
allowed to include its base class:

struct D : B;

I am not enough of a language lawyer to know why this would not work and
whether it might have problems in the presence of multiple base classes.


Received on 2020-02-21 11:56:28