I'm kind of new to c++ and I'm facing memory leaks which made me wonder maybe I didn't understand something right.
I'm having:
.h file
class DeliveryVehicle{
public:
//c'tor
DeliveryVehicle(const char* ID, Quality quality);
//d'tor
virtual ~DeliveryVehicle();
...
protected:
VehicleParcelQueue parcelQueue_;
}
.c file
DeliveryVehicle::~DeliveryVehicle(){
while(!parcelQueue_.empty()) parcelQueue_.pop();
// pop() calls removed element destructor
}
I have a derived class, in which I count on the default destructor, and not implementing a destructor explicitly.
I would like to know, is it ok in case I don't allocate memory in the derived class using "new"?
Additionally, I implemented fixed size queue of my own which inherits the Base Class Queue from STL:
.h file
class VehicleParcelQueue:public std::queue<Parcel*>{
public:
const static int MaxParcelsNum = 5;
Result push(Parcel*);
};
.cpp file
typedef enum result{SUCCESS = 1,FAILURE = 0} Result;
Result VehicleParcelQueue::push(Parcel* pParcel){
if (size() >= 5) return FAILURE;
else{
queue<Parcel*>::push(pParcel);
return SUCCESS;
}
As can be seen, also In this case, I didn't implement the destructor explicitly. Am I prone to memory leaks?
Maybe pop doesn't calling delete for Parcle but destructor to pointers? thanks
in addition to R Sahu answer, note that std::queue<>
destructor is not virtual, any deletion from a pointer to Base will invoke undefined behavior (for that reason, you should generally not inherit from standard containers).
You should probably review your design, such as using a class member instead of inheritance, and preferring values to pointers if possible :
VehicleParcelQueue
{
...
std::queue<Parcel> queue;
};