Icon Description
While stepping from C to the C++ world, it’s the first pitfall that we encounter – initializing an object with memset. Since memset if faster, we used to initialize objects like this,

CObject obj;
memset( &obj, 0, sizeof(obj));

More than enough for a crash! Because if the class contains virtual functions, then the first 4 bytes holds the pointer to vtable. If we use memset, then the vtable pointer will be overwritten to 0 and it may end up in crash.

But, do you know one thing? The famous MFC framework uses memset to initialize some of its objects such as CDialog, CScrollView etc. Can’t believe? It does, but safely. Without damaging the vtable pointer.

icon_underthehood.jpg
If you check the constructor of CDialog, you can see one macro – AFX_ZERO_INIT_OBJECT();. This macro calls memset internally. See the implementation of macro below.

// zero fill everything after the vtbl pointer
#define AFX_ZERO_INIT_OBJECT(base_class) \
memset(((base_class*)this)+1, 0, sizeof(*this) - sizeof(class base_class));

But it’s safe. Because it skips the vtable ptr.

Icon Note
Don’t try this macro in your source. Because CDialog doesn’t contain any objects as members. It contains just some pointers and handles. If your object contain some class variables as members which contain virtual table, then that vtable ptr may be overwritten. Take care!