Friday, May 27, 2005

Pure virtual destructors

Ah! I can't stay away from C++ for long - can I??

Well, I encountered a situation where I needed to use a pure virtual destructor and also a query on the comp.lang.c++ newsgroups. You can read the newsgroup thread here.

OK - So, what's the hue and cry over pure virtual destructors?? To point this out, let me list the characteristics of normal pure virtual functions and then compare pure virtual destructors and the rationale behind them.

1) Pure virtual functions make a class abstract are declared as follows

virtual void someFunc(void) = 0;

> Pure virtual destructors also make a class abstract and are declared (and defined) as follows

virtual ~SomeClass() { // ... } = 0;

2) Pure virtual functions should not have a function body a.k.a definition
> Pure virtual destructors must have a function body. (That's why I've defined in the example above) This is because, in an inheritance heirarchy all destructors are called while destroying a derived class object. If we could leave out the body of a pure virtual destructor, then there would be nothing to call while destroying a derived class baby!

3) A pure virtual function in a base class would make its derived classes abstract unless its defined in the derived classes
> A pure virtual destructor need not be defined in the derived classes and still the derived classes would not be abstract. This is because the compiler would supply the destructor when we don't write one.

So, what's the use of a pure virtual destructor if its so counter-intuitive to pure virtual functions?!?!

Well, you can fall back on a pure virtual destructor to make a class abstract when there are no other candidate member functions that can be made pure virtual. This is much better and recommended rather than having a dummy pure virtual function that might reduce readability!

Ah! Now I feel relieved :-)

No comments:

Post a Comment

What I want to say is: