fork download
  1. #include <iostream>
  2. #include <memory>
  3.  
  4. class Animals
  5. {
  6. public:
  7. virtual void Display() = 0;
  8. virtual ~Animals() = default;
  9. };
  10.  
  11. class Dog : public Animals
  12. {
  13. void Display() override
  14. {
  15. std::cout << "This is Dog!" << std::endl;
  16. }
  17. };
  18.  
  19. class Cat : public Animals
  20. {
  21. void Display() override
  22. {
  23. std::cout << "This is Cat!" << std::endl;
  24. }
  25. };
  26.  
  27. class Goat : public Animals
  28. {
  29. void Display() override
  30. {
  31. std::cout << "This is Goat!" << std::endl;
  32. }
  33. };
  34.  
  35. int main()
  36. {
  37. Animals* animal = new Dog;
  38. animal->Display();
  39. delete animal; // delete at some point to avoid memory leak as Dog is allocated on the heap
  40.  
  41. Cat cat;
  42. animal = &cat;
  43. animal->Display(); // no delete needed, as Cat is allocated on the stack and will cleared when goes out of scope
  44.  
  45. std::unique_ptr<Animals> animal2 = std::make_unique<Goat>();
  46. animal2->Display(); // no delete needed, Goat is allocated on the heap but will be cleared when goes out of scope
  47.  
  48. return 0;
  49. }
Success #stdin #stdout 0s 4452KB
stdin
Standard input is empty
stdout
This is Dog!
This is Cat!
This is Goat!