0

how does this line work assuming b is the base class from which D1 is derived and Tell is a virtual function which is defined in d1 and as well as b

D1 d1;
((D1)((B)d1)).Tell();
Saransh
  • 109
  • 1
  • 8
  • This doesn't seem right, as C-Style casts tries different C++ casts in an order but [`dynamic_cast` isn't one of those](http://stackoverflow.com/a/17598055/183120). – legends2k Oct 19 '13 at 13:33
  • 1
    I se no `b` in your code. Did you mean `B`? – jalf Oct 19 '13 at 13:35

2 Answers2

2

It probably doesn't work, unless D1 has a constructor to convert from B. If that's the case, it "works" by creating a temporary object and calling the function on that (after creating yet another temporary of type B); which is almost certainly not what you want to do.

If you're actually casting to pointer or reference types, then it "works" if d1 has type D1 since the conversions cancel each other out; but if it's another type, you're casting to the wrong type and invoking undefined behaviour.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
-1

You mentioned d1 is derived from b but have't mentioned about D1. Assuming b is the base class & d1, D1 both derived from b & Tell is virtual, so it will call the body of Tell from D1

Satinder Sidhu
  • 373
  • 3
  • 9