fork download
  1. #include <iostream>
  2.  
  3. class Animal
  4. {
  5. public:
  6. virtual ~Animal(){}
  7. };
  8.  
  9. class Dog : public Animal
  10. {
  11. public:
  12. virtual void woof() { }
  13. };
  14.  
  15. class Cat : public Animal
  16. {
  17. public:
  18. virtual void meow() { }
  19. };
  20.  
  21. int main()
  22. {
  23. Cat felix;
  24. Cat* the_cat = &felix;
  25. // "normal" cast, which disallows casting between unrelated class hierarchies,
  26. // but while downcasting assumes the programmer knows
  27. Dog* the_dog_1 = static_cast<Dog*>(the_cat);
  28. // your cast with testing validity at runtime
  29. // (doesn't fail at compile time, because there may be a CatDog
  30. // derived from Cat and Dog in other translation unit)
  31. Dog* the_dog_2 = dynamic_cast<Dog*>(the_cat);
  32. // "everything goes" byte reinterpretation cast
  33. Dog* the_dog_3 = reinterpret_cast<Dog*>(the_cat);
  34.  
  35. the_dog_1->woof();
  36.  
  37. if(the_dog_2)
  38. the_dog_2->woof();
  39.  
  40. the_dog_3->woof();
  41. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp: In function 'int main()':
prog.cpp:27:44: error: invalid static_cast from type 'Cat*' to type 'Dog*'
  Dog* the_dog_1 = static_cast<Dog*>(the_cat);
                                            ^
stdout
Standard output is empty