fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <memory>
  4.  
  5. class Base {
  6. public:
  7. virtual void go() {
  8. std::cout << "I am the base class" << std::endl;
  9. }
  10. };
  11.  
  12. typedef std::shared_ptr<Base> base_ptr;
  13.  
  14. class DerA : public Base {
  15. void go() {
  16. std::cout << "I am the first derivative" << std::endl;
  17. }
  18. };
  19.  
  20. class DerB : public Base {
  21. void go() {
  22. std::cout << "I am the second derivative" << std::endl;
  23. }
  24. };
  25.  
  26. class UnrelatedClass {
  27. public:
  28. std::vector<base_ptr> vec;
  29. void add_to_vec(const base_ptr& thing) {
  30. vec.push_back(thing);
  31. }
  32. };
  33.  
  34. int main() {
  35. UnrelatedClass uc;
  36. uc.add_to_vec(std::make_shared<Base>());
  37. uc.add_to_vec(std::make_shared<DerA>());
  38. uc.add_to_vec(std::make_shared<DerB>());
  39.  
  40. for (auto thing : uc.vec) {
  41. thing->go();
  42. }
  43.  
  44. return 0;
  45. }
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
I am the base class
I am the first derivative
I am the second derivative