How to declare(not define) a class with a derived relationship

Given a class B and its derive class D:

class B {...};

class D :public B {...};

Then in another class C1:


#include "B.h"

//What should write here?


class C1
void ProcessB(B*);
void ProcessD(D*);

#include "C1.h"

void C1::ProcessD(D* pd)

If I write in the place (1):

#include "D.h"

Then no any problem.

However I just use D* in class C1, and I don't need to access any member function or member data of class D(neither delete it (need call destrutor)), so I just only want to declare it to reduce the compilation dependency, so I write (1) for:

class D;

Then compiler said the D* can't convert to B* when calling ProcessB.

By the way, I don't want to change the parameter type of ProcessD() to B* even if it works. For this can prevent I wrongly pass other derived class pointer to this function. And I don't want type cast to convert the pointer type.

So how to tell the compiler D is derived from B under the condition that I only want to declare D?

I have tried this but didn't work in MS VC++ 2005:
class D : public B;
Last edited on
Are you willing to include D.h in C1.cpp?
rollie: Thanks for you reply. Including D.h in C1.cpp should be able to work however it causes C1.cpp dependent on D.h when compiling. So is there any better way?
BTW, I have modified to simply my topic just now.
Last edited on
Unfortunately, you can't do what you are thinking (though I can certainly see the use-case). You could possibly jump through a whole bunch of hoops creating multiple overloads of each method, but really the solution is to include D.h in the C1 implementation.

Also, the likely reason this isn't supported is multiple inheritance. If class D is
class D : public B1, public B2
you can pass a D to code that takes a B2, but in order for that to work, the this pointer has to be adjusted so that the D looks like a B2. If you know 100% that D will always inherit from B first, I think that you can just static cast it to a B in C1.cpp and it will work, but I don't know that the standard guarantees it will work (plus it's really sloppy).
Last edited on
Yes. Either include "D.h", or use cast. I think no other way. Thanks.
Topic archived. No new replies allowed.