C++ Casting Operators

CPP

Going over the Casting Operators in C++

static_cast Operator

Converts to an assigned type based on the type passed into it. It is important to keep in mind that static_cast’s do not check that the output type matches the input type. This means less overhead from type checks but the responsibility falls on the programmer to ensure that the types match.

Name name;
Surname* surname = static_cast<Surname*>(&name);

reinterpret_cast Operator

Convert a pointer of one class to a pointer of another class. Many of its use cases have diminished with compiler updates. You can use it to convert pointers to ints and back to pointers. You can also use it to pass function callbacks around since you can convert function pointers with it. Of course, it’s all very dangerous.

const char* name = "NAMES";
int ptr = reinterpret_cast<int>(name);
const char* samename = reinterpret_cast<const char*>(ptr);

dynamic_cast operator

Performs conversion but only after verification. Where this is useful is when you’re dealing with Polymorphism. It lets you convert and check upcast, downcast and sidecast attempts.

struct Media { virtual void SaveToLibrary() { } };
struct Software { };
struct Movie : Media { int runningTime; };
struct Game : Media { int numPlayers; };
struct VideoGame : Game, Software {  };

To demonstrate, we need some classes setup for polymorphism i.e. at least one virtual function exists. If none can be set, the virtual destructor should be used.

    VideoGame contra;
    Game* game = &contra;
    Software* sw = dynamic_cast<Software*>(game);
    if (sw) cout << "This Game is Software" << endl; // Sidecast!

    Media* media = &contra;
    // Movie* movie = media; //Invalid conversion
    Movie* movie = dynamic_cast<Movie*>(media);
    if (movie) cout << "This Media is a Movie!" << endl; // It's not

Above, we’re using dynamic_cast to take a single type and morph it into other types. We’re able to do a sidecast where a Game becomes Software even though they aren’t related in the hierarchy. We also attempt to turn our Media into a Movie but fail since the Media was originally a ~VideoGame. It’s worth noting that in the above code, dynamic_cast is skipped for upcasts but it most certainly can be used for it.

const_cast operator

Convert one type to the same type and modify its const-ness. Can also affect volatility. Using this to purely modify a const object with this is not a good idea.

    int value = 10;
    const int& fixed = value;
    //fixed++; // get error
    int& modifiable = const_cast<int&>(fixed);
    modifiable++; //everything's been incremented
    // Above 2 lines can be condensed to: const_cast<int&>(fixed)++;

Here we remove the const qualifier on a value.