#include <iostream>
#include <memory>
#include <vector>
#include <algorithm>
using namespace std;
// Header file of the Base class
class Particle{
int a;
public :
Particle( ) { } // some constructor
virtual ~Particle( ) { cout << "Particle dies" << endl; } // virtual destructor because of polymorphism
virtual void function( ) { cout << "Bing" << endl; } // some random function for demonstration
} ;
// Header file of the Derived class
class Electron : public Particle{
int b;
public :
Electron( ) { }
~Electron( ) { cout << "Electron dies" << endl; }
void function( ) override { cout << "Bang" << endl; } // some random function for demonstration
// additional things, dynamic_cast<>s, whatever
} ;
int main( ) {
int count= 3 ;
// If want to create arrays the old way
cout << "Allocating non polymorphic arrays, for the record" << endl;
{
std:: unique_ptr < Particle, std:: default_delete < Particle[ ] >> particle( new Particle[ count] ) ;
std:: unique_ptr < Electron, std:: default_delete < Electron[ ] >> electrons( new Electron[ count] ) ;
}
// alternative approach
cout << endl<< endl<< "Alternative approach:" << endl;
vector< Electron> myelectrons( count) ; // object store
vector< Particle* > ve( count, nullptr) ; // polymorphic adaptor
transform( myelectrons.begin ( ) , myelectrons.end ( ) , ve.begin ( ) , [ ] ( Particle& e) { return & e; } ) ;
for ( auto x: ve)
x- > function( ) ;
return 0 ;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8bWVtb3J5PgojaW5jbHVkZSA8dmVjdG9yPgojaW5jbHVkZSA8YWxnb3JpdGhtPgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKCi8vIEhlYWRlciBmaWxlIG9mIHRoZSBCYXNlIGNsYXNzCmNsYXNzIFBhcnRpY2xlewoJaW50IGE7IApwdWJsaWM6CiAgICBQYXJ0aWNsZSgpIHt9ICAgICAgICAgICAgLy8gc29tZSBjb25zdHJ1Y3RvcgogICAgdmlydHVhbCB+UGFydGljbGUoKSB7IGNvdXQgPDwgIlBhcnRpY2xlIGRpZXMiPDxlbmRsOyB9ICAgIC8vIHZpcnR1YWwgZGVzdHJ1Y3RvciBiZWNhdXNlIG9mIHBvbHltb3JwaGlzbQogICAgdmlydHVh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