fork download
  1. #include <iostream>
  2. #include <memory>
  3. #include <vector>
  4. #include <algorithm>
  5. using namespace std;
  6.  
  7.  
  8. // Header file of the Base class
  9. class Particle{
  10. int a;
  11. public:
  12. Particle() {} // some constructor
  13. virtual ~Particle() { cout << "Particle dies"<<endl; } // virtual destructor because of polymorphism
  14. virtual void function() { cout <<"Bing"<<endl; } // some random function for demonstration
  15. };
  16.  
  17. // Header file of the Derived class
  18. class Electron : public Particle{
  19. int b;
  20. public:
  21. Electron() {}
  22. ~Electron() { cout << "Electron dies"<<endl; }
  23. void function() override { cout <<"Bang"<<endl; } // some random function for demonstration
  24.  
  25. // additional things, dynamic_cast<>s, whatever
  26. };
  27.  
  28. int main() {
  29. int count=3;
  30.  
  31. // If want to create arrays the old way
  32. cout << "Allocating non polymorphic arrays, for the record"<<endl;
  33. {
  34. std::unique_ptr<Particle, std::default_delete<Particle[]>> particle(new Particle[count]);
  35. std::unique_ptr<Electron, std::default_delete<Electron[]>> electrons(new Electron[count]);
  36. }
  37.  
  38. // alternative approach
  39. cout <<endl<<endl<<"Alternative approach:"<<endl;
  40. vector<Electron>myelectrons(count); // object store
  41. vector<Particle*>ve(count, nullptr); // polymorphic adaptor
  42. transform(myelectrons.begin(), myelectrons.end(), ve.begin(), [](Particle&e){return &e;} );
  43. for (auto x: ve)
  44. x->function();
  45.  
  46. return 0;
  47. }
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
Allocating non polymorphic arrays, for the record
Electron dies
Particle dies
Electron dies
Particle dies
Electron dies
Particle dies
Particle dies
Particle dies
Particle dies


Alternative approach:
Bang
Bang
Bang
Electron dies
Particle dies
Electron dies
Particle dies
Electron dies
Particle dies