AnsweredAssumed Answered

dynamic_cast issue when downcasting and virtual inheritance is involved

Question asked by mastermind3001 on Jan 27, 2012
Latest reply on Feb 1, 2012 by CraigG

This appears to be a compiler bug.


I've attached an example project which defines three C++ classes, A, B, and Z. B inherits from A, and A virtually from Z. I create a B, dynamic_cast it to an A, and then back to B, and the pointer I get back is wrong. When A inherits from Z without using "virtual", everything works fine.



Original: 4286596048 (&bObj), b = 7

aObjPtr: 4286596048 (upcast), a = 6

bObjPtr: 4286596032 (downcast to original), b = 0



VisualDSP++ 5.0 Update 10

BF518-EZ-BOARD 1.0


Windows 7 64-bit SP 1


Project: the most basic project with one C++ source file and otherwise defaults for everything except enabling RTTI/exceptions.


Source (CastingTest.cpp):


#include <stdint.h>

#include <stdio.h>


class Z {


  Z() : z(5) {}

  virtual int func() { return z; }

  int z;



// Breaks when Z is virtual.

class A : public virtual Z {


  A() : a(6) {}

  virtual int func() { return a; }

  int a;



class B : public A {


  B() : b(7) {}

  virtual int func() { return b; } // Removing this line also fixes things.

  int b;



int main(void)


  B bObj;

  A* aObjPtr = dynamic_cast<A*>(&bObj);

  B* bObjPtr = dynamic_cast<B*>(aObjPtr);


  printf("Original: %u (&bObj), b = %i\n", (uintptr_t)&bObj, bObj.b);

  printf("aObjPtr: %u (upcast), a = %i\n", (uintptr_t)aObjPtr, aObjPtr->a);

  printf("bObjPtr: %u (downcast to original), b = %i\n", (uintptr_t)bObjPtr, bObjPtr->b);


  return 0;