fork download
  1. #include <iostream>
  2. #include <memory>
  3. #include <vector>
  4.  
  5. class Parent
  6. {
  7. public:
  8. virtual ~Parent() = default;
  9. virtual void dofunc() = 0;
  10. };
  11.  
  12. class Child1: public Parent
  13. {
  14. public:
  15. void dofunc()
  16. {
  17. std::cout << "Child 1\n";
  18. }
  19. };
  20.  
  21. class Child2: public Parent
  22. {
  23. public:
  24. void dofunc()
  25. {
  26. std::cout << "Child 2\n";
  27. }
  28. };
  29.  
  30. void myFunc(Parent *c)
  31. {
  32. c->dofunc();
  33. }
  34.  
  35. int main()
  36. {
  37. std::vector<std::unique_ptr<Parent>> v;
  38.  
  39. v.push_back(std::make_unique<Child1>()); // use smart pointers to manage the alloccation
  40. v.push_back(std::make_unique<Child2>());
  41.  
  42. myFunc(v[0].get());
  43. myFunc(v[1].get());
  44. //we could just as easily
  45. v[0]->dofunc();
  46. // in most cases, but sonmewtimes it's good/useful to hide what's really going on
  47.  
  48. return 0;
  49. }
  50.  
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
Child 1
Child 2
Child 1