Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A conversion that C-style cast can handle, but C++ casts cannot

Tags:

c++

c

casting

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?

like image 402
Mikhail Avatar asked Nov 24 '15 17:11

Mikhail


1 Answers

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.

like image 91
Cheers and hth. - Alf Avatar answered Oct 30 '22 10:10

Cheers and hth. - Alf