I know that I can do:
class Foo;
but can I forward declare a class as inheriting from another, like:
class Bar {};
class Foo: public Bar;
An example use case would be co-variant reference return types.
// somewhere.h
class RA {}
class RB : public RA {}
... and then in another header that doesn't include somewhere.h
// other.h
class RA;
class A {
public:
virtual RA* Foo(); // this only needs the forward deceleration
}
class RB : public RA; // invalid but...
class B {
public:
virtual RB* Foo(); //
}
The only information the compiler should need to process the declaration of RB* B:Foo()
is that RB
has RA
as a public base class. Now clearly you would need somewhere.h if you intend to do any sort of dereferencing of the return values from Foo
. However, if some clients never calls Foo
, then there is no reason for them to include somewhere.h which might significantly speed compilation.
A forward declaration is only really useful for telling the compiler that a class with that name does exist and will be declared and defined elsewhere. You can't use it in any case where the compiler needs contextual information about the class, nor is it of any use to the compiler to tell it only a little bit about the class. (Generally, you can only use the forward declaration when referring to that class without other context, e.g. as a parameter or return value.)
Thus, you can't forward declare Bar in any scenario where you then use it to help declare Foo, and it flat-out doesn't make sense to have a forward declaration that includes the base class -- what does that tell you besides nothing?