c++inheritancestandardsforward-declarationprivate-inheritance

Can I omit non-public inheritance for forward-declaration of classes?


Let's say I have a piece of code like this:

// Foo.h:
class Incomplete; // the forward-declaration
class Foo {
  void bar(Incomplete&); // doesn't really matter
};
// Foo.cpp:
class Incomplete : private Baz {
};
void Foo::bar(Incomplete&) {
}

Is forward-declaring classes like in Foo.h standard-compliant? If it is, since which language version? What about the same for protected inheritance?


Solution

  • A forward declaration of a class is required to omit inheritance. You cannot write

    class Incomplete : private Baz;
    

    even if you wanted to.

    The purpose of a forward declaration is to simply indicate that a particular name in a particular namespace refers to a class. Specifying the base class is part of the definition since it gives information about the class's layout in memory.