Virtual Destructors

Interview questions often ask about virtual destructors and why they are needed. It’s one of those funny things about C++ that unless you have specifically been shown, you just might not realise you need to know.

So why do you need a virtual destructor?

Essentially, you need a virtual destructor to make sure that ALL the relevant destructors are called when you delete an object via a base class pointer.

Huh?

Well, that actually sounds far more complicated than it is.

Let’s use an example to make it easier. Imagine you have a base class called Container and a sub class called CardboardBox. You create a CardboardBox, and then use the base class pointer to access it (why? see below). When you’re all done, it’s time to delete your object.

Now, the base class doesn’t do much in the way of clearing up, but the subclass (the cardboard box), can be recycled.

So, when your base class destructor is virtual, deleting the base class pointer will call the sub class destructor without you having to do anything extra – and the box will be recycled as if by magic.

If, however, your base class destructor is not virtual, only the base class destructor will get called and the recycling will not happen. Very bad for the environment.

Ouch.

Let’s see this in action with a code example:

#include <iostream> 
using namespace std;

class Container
{
public:
	Container() {};
	virtual ~Container()
	{
		cout << "Base class destructor called - not much to do." << endl;
	};
};

class CardboardBox: public Container {
public:
	CardboardBox() {};
	~CardboardBox()
	{
		cout << "Sub class destructor called - let's recycle the cardboard!" << endl;
	};
};

int main()
{
	CardboardBox* box = new CardboardBox;

	Container* p = box;

	delete p;

	return 0;
}

When the destructor is virtual (as it should be), the output of this program is as follows:

virtual1

You can see that both the sub class and the base class destructors have been called, and you have been a green and conscientious consumer.

However, if you remove the ‘virtual’ keyword from the base class destructor, the output changes to this:

virtual2

Oh dear. No one recycled their cardboard today.

So you see, making your base class destructors virtual will help keep everything nice and tidy. Which is of course, just how we like it 🙂

Why are you using a base class pointer to access the cardboard box?

This is the key to polymorphism in C++. You can use a base class to interface with objects without knowing what they are. So in this example you can talk to objects via the base class (Container), and you don’t need to specifically know whether they are cardboard boxes, metal boxes, or wicker baskets!

I’ve a fuller explanation of polymorphism here.

Linux Commands: nl

There is an incredible selection of little Linux commands that will do all sorts of things to your files, standard output and programs. Now and again I’m going to pick one out and have a play because you just never know when a little tool already exists that will do exactly what you need.

Today I’m going to look at nl, which prepends line numbers to any file that you pass it to.

Remember this one as “number lines” (think Numberwang on Peep Show). Don’t get confused and use ln, because that is for linking files 🙂

Okay, so I’ve got a little C program, and you can view the source code on the command line with cat:

cat main.c

cat

Very nice. Now let’s output the file with nl instead:

nl main.c

nl1

Look at that! Numbers down the side. Isn’t that handy?

But that’s not all.

Say you wanted to number all the lines – not just the ones with source code. This time use the flag -ba:

nl -ba main.c

nl2

Nice.

Now let’s go a little retro, start the numbering at 10 and increase it by 10 each time (BBC Basic anyone?).

Use -v to start at your required number and -i to specify the increment:

nl -ba -v10 -i10 main.c

nl3

You can even add a string in front of each line.

Here I’ve added a colon after each number:

nl -ba -v10 -i10 -s": " main.c

nl4

The only thing missing really is the option to add disco colours and flashing text 😉

Check out the man page for full details on all the options (man nl).

Turn On Line Numbers in Eclipse [Luna]

Personally, I’m not sure what any code editor thinks it is doing by not having line numbers switched on by default.

But, each to their own, so if you want to see your line numbers in Eclipse and you just can’t find out where on earth to turn them on, aaargh! Don’t panic.

Just go to:

Window -> Preferences -> General -> Editors -> Text Editors

And check the handy “Show line numbers” box:

eclipselinenumbers

Then, take a deep breath, and feel much better than you can now see which line of code you are editing at any given time.

Save GDB Breakpoints

It wasn’t that long ago (well, okay, it was back in 2010, but anyway), that using the GDB debugger left you with the issue of how to maintain your breakpoints from one debug session to the next.

After carefully adding breakpoints, and spending time getting them in just the right place, it was a real headache to have to repeat that exercise the next time you ran a debug session – especially when you were dealing with one of those nefarious bugs that can take days to track down.

I used to list my breakpoints, copy and paste them to a file, then add them to the .gdbinit file for the next time I wanted to use them. Annoying.

Well, in case you’ve been doing the same, or if it never even occurred to you that you could preserve your perfectly positioned breakpoints between sessions, I thought I’d mention that since gdb 7.2 you’ve been able to save your breakpoints in one single step with the following command:

save breakpoints myfile.txt

Phew!

And when you want to use them again, just import them with:

source myfile.txt

Here’s a quickie screenshot where I’ve added 4 breakpoints, saved them to a bp.txt file, deleted them, listed breakpoints to show none present, then re-added them and listed them to show them after import.

Great stuff 🙂

gdb_savebreakpoint