fork download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. class Car
  5. {
  6. public:
  7. virtual ~Car() {};
  8.  
  9. virtual void drive() {};
  10. };
  11.  
  12.  
  13. class Porsche : public Car
  14. {
  15. public:
  16. virtual void drive()
  17. {
  18. std::cout << "Porsche just drives but not fast!" << std::endl;
  19. };
  20.  
  21. void driveFast()
  22. {
  23. std::cout << "Porsche drives fast!" << std::endl;
  24. };
  25. };
  26.  
  27.  
  28. class Ford : public Car
  29. {
  30. public:
  31. virtual void drive()
  32. {
  33. std::cout << "Ford just drives but not fast!" << std::endl;
  34. };
  35. };
  36.  
  37. int main () {
  38.  
  39. std::vector<Car *> cars;
  40. cars.push_back(new Porsche()); /* implicit up-cast */
  41. cars.push_back(new Ford()); /* implicit up-cast */
  42.  
  43. Car * porscheAsCar = cars.at(0);
  44. Porsche * porsche = dynamic_cast<Porsche *>(cars.at(0));
  45.  
  46. porscheAsCar->drive();
  47. porsche->drive();
  48. porsche->driveFast();
  49.  
  50. delete cars.at(0);
  51. delete cars.at(1);
  52.  
  53. return 0;
  54. }
  55.  
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
Porsche just drives but not fast!
Porsche just drives but not fast!
Porsche drives fast!