C++ Programming: Lesson about virtual methods and base class destructors…
I wrote a test program so that I can better understand how boost::bind works, because I needed to grok how to use the standard library’s algorithm classes better (for example, std::for_each).
Here is my code:
http://www.dooglio.net/source/bind_test.cpp.html
An interesting consequence I found when I attempted to call a pure virtual method on my base class MainTestBase::FooBar from MainTestBase’s constructor. Of course, the result is a runtime error + abort, with the message “pure virtual method called.”
It turns out that the C++ standard has something to say about this:
From C++ Standard 10.4 [class abstract]:
Member functions can be called from a constructor (or destructor) of an abstract class; the effect of making a virtual call (10.3 [class.virtual]) to a pure virtual function directly or indirectly for the object being created (or destroyed) from such a constructor (or destructor) is undefined.
So, there you go. Lesson learned.
PS: I’ve been programming professionally in C++ for almost 20 years now and I still learn new things about the language! For example, I found out last week that pure virtual methods may have method bodies and that this requires the deriving class to provide an implementation. Nifty.


