virtual methods in Constructors == Havok

Recently I wrapped up a Test Driven Development course for some co-workers in Beaverton, Oregon which went quite well (some good enthusiasm from the folks there). As always every time I teach or rather ‘share’ something with people I end up learning something new (such as Mock Object frameworks). This time I wanted to point out a very interesting deviation between programming languages in reference to virtual methods being called in constructors (and depending on your language destructor’s too).

In our environment here in Kelowna, BC we use Borland Developer Studio 2006 (C++), as well as Visual Studio 2003 (C#). In the past a colleague and myself worked on a small Java project in Workforce 5.x. The link I am about to mention brings together all 3 worlds.

With that said check this out:

Using virtual methods is important in TDD. Since TDD is a big part of code quality, I find it essential to know what your language does as it may come to bite you in unexpected ways otherwise. Our team has created a lot (in the past year) of C++ tests (both Unit and FIT). In C++ we have a HUGE deviation in how virtual methods get handled in constructors and destructor’s, BUT one caveat for those using Borland’s flavour of C++:

If you derive your class from the VCL class TObject, your virtual method’s will get called in the same order as C# (since TObject is in fact a Pascal class and does NOT follow C++ convention). This was found recently went a collegue create a new unit test around a pure C++ class and started getting runtime errors about a pure virtual method getting called!

To summarize, I find the link mentioned above interesting as its rare to see Java painted in such a negative way, but of course that all depends on what perspective you come from.


Comments are closed.