3

After about 6 o 7 years programming nearly exclusively on C++, I've discovered that:

struct A
{
   virtual ~A() = 0; // Abstract class
};

A::~A() {}

struct B : virtual A
{};

int main()
{
    A* a = new B;
    (void)static_cast<B*>(a);

    return 0;
}

throws a compiler error, because the standard doesn't allow to make a static cast from a pointer to a virtual base class. I assume that that's related to the memory layout associated to a virtual base class, but I would like to know the details.

curiousguy
  • 8,038
  • 2
  • 40
  • 58
ABu
  • 10,423
  • 6
  • 52
  • 103

1 Answers1

0

The reason is, the memory image of virtual A within B and that of A might differ. Without allowing it to differ, the well-known 'dared diamond' could not be solved (well, at least not easily, since we cannot request A to be aware of this and set up an ABI that's preferable to us). Think of virtual A as having a virtual function for each function and member access of A in B. It's not necessarily implemented like that, but you might model it that way.

lorro
  • 10,687
  • 23
  • 36