It is said that C-style cast just tries to apply different combination of C++ casts and the first allowed combination is used. However, I have a feeling that I heard that there are situations that only C-style cast can handle, while none of combination of C++ casts are allowed.
Am I wrong? Is that true that any C-style cast in any context (in C++) can be replaced with a proper combination of C++ casts?
UPD Thanks to Cheers and hth. - Alf, we have an example that C++ casts cannot handle in the meaning they cannot produce defined and expected behavior. Advanced question is to provide an example which C++ casts cannot handle meaning it cannot be even compiled?
Cast to inaccessible base can only be expressed as a C style cast (one of the syntactic variants). In that context it is equivalent to a static_cast
, which may change the address, except that static_cast
can't access the base.
Example:
struct Base
{
int x = 42;
};
struct Oh_my
: private Base
{
virtual ~Oh_my() {}
};
#include <iostream>
using namespace std;
auto main() -> int
{
Oh_my o;
cout << "C cast: " << ((Base&)o).x << endl;
cout << "reinterpret_cast: " << reinterpret_cast<Base&>(o).x << endl;
}
Output with MingW g++ in Windows 7:
C cast: 42 reinterpret_cast: 4935184
But since it's pretty Undefined Behavior, the last output operation could just crash.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With