fork download
  1. #include <iostream>
  2. #include <memory>
  3. #include <vector>
  4. using namespace std;
  5.  
  6. struct Move { virtual void show() { cout <<"Move"<<endl; } };
  7. struct CaptureMove : Move { void show() override { cout <<"CaputreMove"<<endl; } };
  8.  
  9. int main() {
  10.  
  11. // Solution 1 : raw pointers : danger
  12. vector<Move*> mp;
  13. mp.push_back (new Move); // attention, you have to delete it ofr memory will leak
  14. mp.push_back (new CaptureMove);
  15. for (x:mp) { // you have to take care of deletion, but are you sure the vector
  16. delete x; // was not copied and pointers are still needed somewhere else ?
  17. }
  18.  
  19. // Solution 2 : smart pointers <= recommended !
  20. vector<shared_ptr<Move>> m;
  21. m.push_back(make_shared<Move>());
  22. m.push_back(make_shared<CaptureMove>());
  23. m.push_back(make_shared<Move>());
  24.  
  25. for (auto x:m)
  26. x->show();
  27.  
  28. // your code goes here
  29. return 0;
  30. }
Success #stdin #stdout 0s 3464KB
stdin
Standard input is empty
stdout
Move
CaputreMove
Move