Friday, April 10, 2015

Overview

Lets say you have a Animal class and a Dog class. You make a pointer to Animal animal_ptr and you make it point to a Dog object.

Now you make a pointer to Dog and you make it point to animal_ptr. The compiler will complain. What should you do? You should cast it because you know that animal_ptr already points to a Dog object. You can find out more about casting here.

Content

C Style Cast

1
2
3
4
5
Animal* animal_ptr = new Dog("Honey");
Dog* dog_ptr = (Dog)animal_ptr;

int i = 3;
Dog* dog2_ptr = (Dog)i; // will compile

Static Cast

1
2
3
// Evaluated at compile time
Animal* animal_ptr = new Dog("Honey");
Dog* dog_ptr = static_cast<Dog>(animal_ptr); 

Dynamic Cast

1
2
3
// Evaluated at runtime, will return nullptr if it doesnt work
Animal* animal_ptr = new Dog("Honey");
Dog* dog_ptr = dynamic_cast<Dog>(animal_ptr); 

Const Cast

1
2
3
// removes const
const char* const_str = "Honey";
char* normal_str = const_cast<char*>(const_str);

Reinterpret Cast

1
2
3
int anInt = 4;
// takes the bits from anInt and puts them into a double
double aDouble = reinterpret_cast<double>(anInt);

Random Posts