Casting

5 different casts:

  • static

  • dynamic

  • reinterpet

  • const

  • C-style

#include <iostream>

class Fighter{};
class Ninja: public Fighter{};
class Zombie: public Fighter{};

int main(){
    Ninja* ninja = new Ninja;
    Fighter* f1 = ninja;//implicit cast, upcast is fine
    Ninja* n = f1; //can't go back, error

    delete ninja;
    return 0;
}

Ninja* n = f1 is an compile time error and can't go back why? Because f1 could have been a Zombie and not a Ninja. Look what happens here

So basically we must cast

(Ninja*)f2 is casting. But this is DANGEROUS!. If we try to access data members or functions that Ninja has and not Zombie it results in unexpected behaviour.

Dynamic Cast

source type is not polymorphic

Remember! Dynamic Casting only polymorphic types

Lets add a virtual function to Fighter

and now well get this

It know by looking at RTTI.

Static Cast

Let look at 3 examples

1st Example

or

to prevent this we can use static_cast<>() which gives you a compile time checking ability, C-Style cast doesn't.

2nd Example

The following should result in an error but doesn't

Now if we change this to a static_cast

3rd Example

The following should result in an error but doesn't

Now if we change this to a static_cast

Creditsarrow-up-right

reinterpret_cast

  • It is used to convert one pointer of another pointer of any type, no matter either the class is related to each other or not.

  • It does not check if the pointer type and data pointed by the pointer is same or not.

great-power.jpg?w=640

Creditsarrow-up-right

Here each time before we cast we have to know the exact type. This is useful is we want to do really low level work.

If we where to mess up lets say like here

Here we didn't get a or 1 (true)

C-style

Tries to do the following casts, in this order:

  • const_cast (1st)

  • static_cast

  • static_cast followed by const_cast

  • reinterpret_cast

  • reinterpret_cast followed by const_cast (last)

RTTI typeid (Run-time type info)

  • dynamic_cast

  • typeid

typeid(obj) or typeid(obj).name()

Here we added a function that checks if two fighters are the same

Seems better suited if we don't want to cast and only want to compare.

  • Has overhead and is slower since this runs at runtime

Last updated