Destuctors and virtual [Discussed on the visualiser during lecture 7] Consider a program containing: class A { A() { } ~A() { } ... } class A : public B { B() { } ~B() { } ... } B *x = new B; A *y = B; // cast to pointer-to-supertype. Note that x and y point to the same object, but have different types. If we now do: delete x; then this uses B's destructor code as expected. BUT, if we say: delete y; then this uses the destructor code for A on an object which was allocated and constructed as a B. This risks disaster (including space leaks e.g. if constructor B() allocates storage and stored a pointer to it in a field of B, since destructor ~A() cannot even access fields of B). The solution to this is that destructors should be marked virtual if there is any chance of an object being freed at a subtype of the allocating constructor's type. With virtual ~A() { } instead of the above code, then the effect of "delete x;" and "delete y;" coincide as expected in this example. Note that it's not necessary (but still good practice) to also write virtual ~B() { } ============= Typo: the notes for lecture 7 have an omitted ";" in slide 11 after the ~Stack() destructor: ~Stack(); // should generally be virtual