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.

Tuesday, April 8, 2008

[win32] Ascii, Unicode, Scan code, Virtual key

... and other keyboard nightmares :-)

I found two very useful functions in the Win32 API: ToUnicodeEx and ToAsciiEx. It converts from a virtual key code and a scan code to a unicode or ascii character. It can be used directly from a WM_KEYDOWN (or KEYUP) message.

Here is a quick code snippet:

uint scancode = (lParam >> 16) & 0xFF;
BYTE keyboardState[256];
char charvalue[2];
if (ToAsciiEx(wParam, scancode, keyboardState, (LPWORD)&charvalue[0], 0, GetKeyboardLayout(0)) == 1) {

Also check out this blog for more info.