C++ Tips, Vol ?

I come across this every so often and still get surprised by it every time. So I figured I’d impart a bit of my hard-earned C++ knowledge so that more people would be familiar with the phenomenon.

Basically, in C++, you need to be sure that base classes don’t require anything from subclasses in their destructor activities. It sounds obvious, but it can pop up in surprising ways.

Say you have a subclass of KListView (we’ll just call it FooListView), and a corresponding subclass of KListViewItem, FooListViewItem. Also assume that you’ve not been praying to the OO gods, and the FooListViewItem is a friend of the FooListView, and accesses the FooListView in its constructor and destructor (like for debugging, or so the FooListView can easily hold data on its FooListViewItems no matter how they were created).

Normally this would work well enough, but during shutdown, as the FooListView is being destructed, it gets destructed starting at the subclasses, and working towards the base. In this case, the destructor would run in this order: ~FooListView() -> ~KListView() -> ~QListView() -> etc. Now, if the FooListView doesn’t delete its little FooListViewItems, what happens? They will still be present when the QListView destructor run, and QListView will happily delete them for you.

But wait! Remember how the FooListViewItems accessed their parent FooListView? The FooListView is now gone, only the QListView methods are valid. So you will get a crash on shutdown if you are not very careful, and remember to delete all FooListViewItems from within the FooListView destructor.

There are other ways that having Qt handle memory management for you can bite you, but they usually are typically due to “poor programming practices”. However, we all have to perform a few hacks in any program of more than minimal complexity, so it is something to keep in mind the next time you have two classes that are innately related to each other.