Wednesday, April 9, 2008

[code] pure virtual function call

Calling a virtual method from a constructor is a very bad idea. Indeed, this can easily result in the 'pure virtual function call' runtime error. This is well explained here. Worse, if the method is not abstract it will call the method from the parent class, instead of calling the specialized one. It is worse because this will probably not directly trigger an error. Now, this 'issue' does in fact make sense: In the constructor of the parent class, the specialized class is not yet initialized. Hence, how could one of its method be called? Therefore, if you need to call a virtual method from a parent class constructor, you are probably facing a problem in your code design.

Nevertheless, I actually came accross an interesting variant of this issue, involving a thread. My parent class, A, is creating a thread in its constructor. The thread execution later involves calling a virtual method of A, which is of course meant to be implemented by inheritance.

The funny thing is that depending on 'how long it takes' before the thread calls the virtual method, we may - or may not - still be in the constructor of A. So, sometimes, this will produce the 'pure virtual call' error, sometimes not. Needless to say I was a bit puzzled the first time :-)
The solution was simply to implement a lock mechanism to make sure the thread calls the virtual method after the constructor executed.

No comments:

Post a Comment