fork(4) download
  1. #include <iostream>
  2. #include <vector>
  3. #include <memory>
  4. using namespace std;
  5.  
  6. class Shape {
  7. public:
  8. virtual void draw() { cout<<"Not implemented yet, but making it abstract wouldn't compile"<<endl;}
  9. virtual ~Shape() {};
  10. };
  11. class Rectangle : public Shape {
  12. public:
  13. void draw() override { cout<<"Rectangle"<<endl;}
  14. };
  15. class Circle : public Shape {
  16. public:
  17. void draw() override { cout<<"Circle"<<endl;}
  18. };
  19.  
  20. int main() {
  21. cout << "Demo of slicing:"<<endl;
  22. vector<Shape> vs; // no pointers, slicing
  23. vs.emplace_back(Rectangle());
  24. vs.emplace_back(Circle());
  25. vs.emplace_back(Rectangle());
  26. for (auto& x:vs) x.draw();
  27.  
  28. cout << endl<<"Demo of polymorphism:"<<endl;
  29. vector<shared_ptr<Shape>> vp; // polymorhpic container
  30. vp.emplace_back(make_shared<Rectangle>());
  31. vp.emplace_back(make_shared<Circle>());
  32. vp.emplace_back(make_shared<Rectangle>());
  33. for (auto& x:vp) x->draw();
  34. // no worry about leaking: shared_ptr will destroy objects when no longer needed
  35.  
  36. return 0;
  37. }
Success #stdin #stdout 0s 4396KB
stdin
Standard input is empty
stdout
Demo of slicing:
Not implemented yet, but making it abstract wouldn't compile
Not implemented yet, but making it abstract wouldn't compile
Not implemented yet, but making it abstract wouldn't compile

Demo of polymorphism:
Rectangle
Circle
Rectangle