Wednesday, 11 September 2013

Why the standard explicate allow C-style cast to convert derived object to inaccessible base sub-object?

Why the standard explicate allow C-style cast to convert derived object to
inaccessible base sub-object?

I just get the information from this cool blog that we can cast the
derived object to inaccessible base class sub-object. On the other hand,
the static_cast cannot be used to do that.
class Base {};
class Derived: private Base {};
void main()
{
Derived d;
Base* b = (Base*)&d; // compile passed.
Base* b = static_cast<B*>(&d); // compile error.
}
Cast the object to private base sub-object will break the private keyword
mean, it make the private object accessible to caller. I assume there is
some reason why C++ standard explicit allow this, and the reason
"compliant to C language" doesn't work to me because there doesn't have
inheriate in C language even you can simulate it, which is unrelated to
this problem.
Can anyone share some thought on this?

No comments:

Post a Comment