2

I seem to have a decent understanding of c++ castings. How static_cast/dynamic_cast work. One concept which I am finding little hard to digest is that:

What is the technical reason for C++ not to allow the down casting using static_cast if derived class is virtually inherited. Say for example :

class B {
}

class D : public B {
}

int main() {
  B* b = new B;
  D* d = new D;
  b = static_cast<B*> d; // Valid
  d = static_cast<D*> b; // Valid

  b = d; // Valid. Implicit casting.
}

But when class 'D' is virtually inherited,

 class D : virtual public B {
 }

then below line breaks,

 d = static_cast<D*> b; // Invalid

Although I have read couple of related posts to it but nothing seems to be the clear answer.

Hemant Bhargava
  • 3,251
  • 4
  • 24
  • 45

0 Answers0