One important rule to remember: Make sure that the destructor is virtual! If the destructor is not virtual, then you will only destroy the base-class, not the derived class. This isn't a problem for very basic classes, but the following would be:
Code:
class base {
public:
base(int ax = 0, int ay = 0) : x(ax), y(ay) {};
~base() { };
private:
int x, y;
};
class derived : public base {
public:
derived(int ax = 0, int ay = 0) : base(ax, ay), size(0), array(0) { };
~derived() { if (array) delete [] array;
void makeArray(int asize) {
size = asize;
array = new int[asize];
};
private:
int *array;
int size;
};
int main()
{
base *bp;
derived *dp = new derived();
dp->makeArray(100);
bp = dp;
deleete bp;
return 0;
}
Edit: Just to clarify - the above example is of course a bit contrived, why not just use dp all the way through. But in a real life scenario where the bp is for example a list of various objects that have their own class, and you delete the entire list as part of a destructor, it would of course delete the contents of this list (presumably), and that would cause the above type of failure, since bp->delete here calls the base destructor. If, on the other hand, we add virtual to the destructor, then it will call THAT OBJECTS destructor, and all will work fine, we don't get any memory leaks.
--
Mats