Jan 24, 2015

[C++] C-style cast

Reference:
http://stackoverflow.com/a/1255015

A C-style cast is basically identical to trying out a range of sequences of C++ casts, and taking the first C++ cast that works, without ever considering dynamic_cast.

Needless to say, this is much more powerful as it combines all of

  1. const_cast
  2. static_cast
  3. reinterpret_cast
but it's also unsafe.
Because it does not use dynamic_cast. 

In addition, C-style casts not only allow you to do this, but they also allow you to safely cast to a private base-class, while the "equivalent" static_cast sequence would give you a compile-time error for that.

[complement:
by cast means casting   Derived ptr to Base ptr.
Not value casting. i.e It's not
--
Base base = (Base)derived;
--
if Derived type is inheriting Base with private.

but this is ok:
--
Base* base = (Base*)&derived;
--
]

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.