Reputation: 933
I have a class hierarchy and i am writing a virtual function in it. Say there are three classes
class A { virtual A* test(); }; ( File A.h )
class B : public A { virtual C* test(); }; ( File B.h )
class C : public A {}; ( File C.h )
Now is it possible for me to avoid including C.h
in B.h
, by doing some kind of forward declaration saying that C
is a sub-class of A
?
Thanks, Gokul.
Upvotes: 1
Views: 2097
Reputation: 58695
You can tell the compiler only three things, in three different ways, about a class C
:
If you want to tell the compiler what the class derives from then you're talking about how the class is structured. You must then show the compiler the class' declaration, there's no other way.
Upvotes: 1
Reputation: 1661
There's no reason to specify B::test() as returning a C* because a C* will always downcast to an A* and any client making correct use of the interface to A will expect an A*. If clients of B expect only C* they should either call a different function or take responsibility for ensuring the returned A* upcasts to a C* using dynamic_cast.
It's also perfectly fine to forward-declare class C before class A and have A::test() return a C* - subclassing doesn't make any difference when declaring pointers to incomplete types in this case.
Upvotes: 0
Reputation: 43400
C/C++ distinguish between complete types and incomplete types. If you forward-declare class C
like this:
class C;
It will be available as an incomplete type, which means you can declare a pointer to it. However, you can't subclass it until C is fully declared, as C is an incomplete type at this point.
You can use class C
inline where you would just use C
. What you want is:
class B : public A { virtual class C* test(); };
Upvotes: 1