Re: Delete of objects whose pointers are stored in an array
On Aug 7, 6:14 pm, nembo kid <nembo@kid> wrote:
I have these classes:
Boss,
CommissionWorker,
PieceWorker,
HourlyWorker
all directly derived from Employeer.
I create a dynamic object (on heap) for each class:
////////////////////////////////////////////////////////////////////
Boss* b = new Boss( "Whites", "Frank", 5, 7, 1971, 1, 9, 1994, 1300);
CommissionWorker* c = new CommissionWorker("Reds", "Tom", 1, 2, 1980, 4=
,
5, 2001, 100, 1000, 2/100 );
PieceWorker* p = new PieceWorker( "Greens", "Bob", 24, 2, 1978, 4, 5,
2001, 10, 100 );
HourlyWorker* h = new HourlyWorker ("Blacks", "Mike", 12, 3, 1967, 13,
4, 2008, 20, 123 );
////////////////////////////////////////////////////////////////////
Then I "put" this pointers into a array of pointer to base class ( so to
upcast ):
////////////////////////////////////////////////////////////////////
Employeer* E[ 4 ] = { b, c, p, h };
////////////////////////////////////////////////////////////////////
After, I want to delete these objects from heap, with delete.
How I can do as simple as possible?
Is it correct following?
////////////////////////////////////////////////////////////////////
for ( int i = 0; i < 4; i++ ) {
delete *( E+i ) ;
}
A little bit off topic, but I would also recommend using a higher form
of abstraction instead of C-style arrays. Just use a std::vector. It's
nearly as fast as an array, is compatible with C code requesting
arrays and it is far more readable and easy to use. Together with the
STL algorithms and the DeleteObject template function class (mentioned
in Scott Meyers Effective STL), vectors holding pointers to dynamic
allocated memory, can be nicely cleaned up like this.
std::vector<Employeer*> e;
e.push_back(b);
e.push_back(c);
e.push_back(p);
e.push_back(h);
std::for_each(e.begin(), e.end(), DeleteObject<Employeer>());
Ofcourse the deletion would be obsolete if you would store shared_ptr
objects instead of raw pointers, already mentioned by mlimber.