Question

I want to ask one simple question in my program i making some kind of system, for dynamic allocation I am taking array of pointers to pointers like this

Vehicle **temp=new Vehical*[countVehicle];

then

temp[countVehicle-1]=new Car();

You must have understood what I am trying to do. The problem comes when deleting memory. Can you please tell me how to delete memory in this case.

Was it helpful?

Solution

for ( int i = 0; i < countVehicle; ++i)
{
    delete temp[i];  // assert destructor is virtual!
}
delete[] temp;

Make sure destructor in base class, Vehicle, is declared virtual so the correct destructor is called when deleting objects via base class pointer, as it take place in example above.

class Vehicle {
public:
    //...
    virtual ~Vehicle() {}
};

However you should consider using a std::vector of smart pointers, e.g

{
  std::vector< boost::shared_ptr<Vehicle> > v;
  v.push_back( boost::shared_ptr<Vehicle>( new Car()));
  v[0]->run(); // or whatever your Vehicle can do
  //...
} // << When v goes out of scope the memory is automatically deallocated.

This will ease memory management.

OTHER TIPS

If you know for sure that the pointers in temp are NULL or a valid allocated Car then:

for(int i = 0; i < countVehicle; ++i)
    delete temp[i];
delete[] temp;

This will only work correctly if Vehicle has a virtual destructor. Otherwise you will not properly destroy each Car.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top