Consider the following piece of code :-
class A {};
class B : private A {};
B* bPtr1 = new B;
// A* aPtr1 = bPtr1; // error
// A* aPtr2 = static_cast<A*>(bPtr1); // error
A* aPtr3 = (A*)bPtr1;
B* bPtr2 = (B*)aPtr3;
The C-style cast discards the private inheritance while both the implicit and static_cast
fail (also dynamic_cast
). Why ?
If C-style casts are just bit-fiddling, how are C++ casts implemented i.e. how do they know the type of inheritance from memory footprint?
After bPtr1 is casted to aPtr3, i will have to use another C-style cast to downcast to B as again both static_cast
and dynamic_cast
fail. So, is bPtr2 guaranteed to be good?
Thanks in advance
See Question&Answers more detail:os