fork download
  1. #include <iostream>
  2. #include <memory>
  3. #include <vector>
  4.  
  5. class IFoo
  6. {
  7. public:
  8. virtual void f() const noexcept = 0;
  9. };
  10.  
  11. using IFooPtr = std::shared_ptr<IFoo>;
  12.  
  13. class Foo : public IFoo
  14. {
  15. public:
  16. void f() const noexcept override
  17. {
  18. std::cout << "Foo" << std::endl;
  19. }
  20. };
  21.  
  22. class NaughtyFoo final : public Foo
  23. {
  24. public:
  25. void f() const noexcept override
  26. {
  27. std::cout << "This Foo is very naughty..." << std::endl;
  28. }
  29. };
  30.  
  31. class GoodFoo final : public Foo
  32. {};
  33.  
  34. int main()
  35. {
  36. const auto naughtyFoo = std::make_shared<NaughtyFoo>();
  37. const auto goodFoo = std::make_shared<GoodFoo>();
  38.  
  39. std::vector<IFooPtr> foos{ naughtyFoo, goodFoo };
  40. for (const auto& foo : foos)
  41. {
  42. if (foo)
  43. {
  44. foo->f();
  45. }
  46. }
  47.  
  48. return 0;
  49. }
Success #stdin #stdout 0.01s 5328KB
stdin
Standard input is empty
stdout
This Foo is very naughty...
Foo