You need to understand that c++ is not c#
To create an object with the default constructor you'll do
CarClass car;
To create an object using another constructor
CarClass car("Mini");
So you can simply do
1 2
|
std::vector<CarClass> car;
car.push_back( CarClass("fiat 600") );
|
when the vector dies, all its elements are eliminated. You do not need to write a destructor in this case (because of the rule of three, you don't need to write an assignment operator or a copy constructor either)
If you want to use polymorphism, then you need to store pointers.
1 2
|
std::vector<CarClass *> cars;
cars.push_back( new sedan("chevrolet") ); //note: sedan is a type of car (class sedan: public CarClass)
|
when the dies, its elements die with it. Note however, that its elements are
pointers; the pointers are eliminated, not what they pointed to.
So you need to create a destructor
1 2
|
for( size_t K=0; K<cars.size(); ++K)
delete cars[K];
|
Also, consider what happens if you do
1 2
|
std::vector <CarClass*> a_parking_lot;
a_parking_lot = cars;
|
Instead of codifying the destructor, copy-constructor and assignment operator yourself, you may store smart pointers (that will
delete
the pointed object correspondingly)