This section of the archives stores flipcode's complete Developer Toolbox collection, featuring a variety of mini-articles and source code contributions from our readers.

 

  How To Not Overwrite Your vTable
  Submitted by



Often when a class has a lot of members that just need to be zero at construction time I use the following code in the constructor.

CSomeClass::CSomeClass()
{
    memset( this, 0, sizeof( CSomeClass ) );
} 




This is perfectly legal, fast for large classes and looks not that stupid at all. But the fun hasn't even started yet. Consider the following class.



class CSomeOtherClass
{
    CSomeOtherClass( void );
    virtual SomeMethod( void );
} 




This class has a virtual method which means that it will contain a vTable. This vTable is created at construction time right before the body of the constructor is entered. Now consider the following constructor implementation.

CSomeOtherClass::CSomeOtherClass()
{
    memset( this, 0, sizeof( CSomeOtherClass ) );
} 


You've just set your vTable to nothing but zeroes. Which means calling SomeMethod() will result in an access violation. Ain't that sweet. It took me actually about 30 minutes, a visit to #flipcode and some thinking to figure out this was happening (since I was using memsets happily for years). If you still want to use memset by the way you could put all your members in a struct and memset that struct (Thanks DoomWiz and Foper). But who would wanna do that :).

Anyway, the #flipcode people told me I should TOTD this so here you go. See you all later, and yeah I know I'm a cheap jeep.

Jaap Suter

The zip file viewer built into the Developer Toolbox made use of the zlib library, as well as the zlibdll source additions.

 

Copyright 1999-2008 (C) FLIPCODE.COM and/or the original content author(s). All rights reserved.
Please read our Terms, Conditions, and Privacy information.