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();
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();
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.
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