views:

190

answers:

3

Hi, 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.

+1  A: 

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(); };
Joey Adams
I think you have failed to notice the virtual function in class A contains a return type of A*. So unless i tell C is a subclass of A, it won't make sense( i don't want to subclass C). If you feel you have answered my question, can you be more clear?
Gokul
@Gokul: I suppose you'll need to include "c.h". In any case, this looks a bit of a design smell.
UncleBens
@UncleBens: I too think, that's the only way. But just thought of checking it out.
Gokul
A: 

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.

drg
A: 

You can tell the compiler only three things, in three different ways, about a class C:

  • That it exists. You do that by forward-declaring the class.
  • How it is structured. You do that by declaring the class.
  • How it behaves. You do that by defining the class' member-functions.

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.

wilhelmtell