views:

98

answers:

2

Possible Duplicates:
C++ pointer multi-inheritance fun.
more c++ multiple inheritance fun

This is a problem that arose from dealing with ref-counted pointer base class and threading fun.

Given:

class A{int x, y;};
class B{int xx, yy;};
class C: public A, public B {int z;};
C c;
C* pc = &c;
B* pb = CtoB(pc);
A* pa = CtoA(pc);

assert(pc == AtoC(pa));
assert(pc == BtoC(pb));

How do I write CtoB and CtoA to get the B & A parts of C?

How to I write AtoC and BtoC to get back the original C?

Thanks!

Why the votes to close?

My previous two questions asked if something was valid (the answer was "no"); this question asks "what is the valid way to do pointer conversion."

+1  A: 

To get the B & A parts of C, you could try:

 B* pbb = static_cast<B*>(pc); 
 A* pba = static_cast<A*>(pc); 

This should be safe.

sinec
To go the other direction, do I have to dynamic cast?
anon
I just noticed that this is asked for 2x just with different title:)
sinec
Yes, to go the other way you'd use a dynamic cast.
Max Lybbert
+3  A: 

You don't need any function, since C only derives once from A and B. Unless you derive from A or B multiple times (without virtual inheritance), you only need to use:

A *pbb = pc;
B *pba = pc;

AtoC and BtoC are only safe through:

C *c = dynamic_cast<C*>(a_or_b_pointer);
rmn
Wouldn't pbb and pba be pointing at the same place then? If so, how can it both be an "A" and a "B" ?
anon
They will not be pointing to the same place. The compiler knows exactly by how much to shift them when transforming C* to A*/B*. You can print the pointers/disassemble to verify.
rmn
I actually have a little challenge for you on this matter, if you're interested: http://cplusplus.co.il/2010/01/20/a-question-of-memory-layout/
rmn
You can't use `dynamic_cast` for downcasts from non-polymorphic base classes. Your cast is ill-formed. Only `static_cast` can be used in this specific case.
AndreyT
You are correct, they'd need to have at least one virtual function (in this case, the destructor is a perfect candidate). As I said, though, the SAFEST approach would be through dynamic_cast, if possible. He could use static_cast, but that will require knowing in advance that it must succeed.
rmn