1

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."

Community
  • 1
  • 1
anon
  • 41,035
  • 53
  • 197
  • 293
  • do you really need a 3rd question with the same theme? http://stackoverflow.com/questions/2158512/more-c-multiple-inheritance-fun and http://stackoverflow.com/questions/2157104/c-pointer-multi-inheritance-fun – Trent Jan 28 '10 at 22:56

2 Answers2

3

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
  • 2,386
  • 1
  • 14
  • 21
  • 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 Jan 28 '10 at 23:04
  • 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 Jan 28 '10 at 23:05
  • 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 Jan 28 '10 at 23:08
  • 2
    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. – AnT stands with Russia Jan 28 '10 at 23:18
  • 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 Jan 29 '10 at 10:37
1

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.

sinek
  • 2,458
  • 3
  • 33
  • 55