I had this conversation with a colleague, and it turned out to be interesting. Say we have the following POD class
struct A {
void clear() { memset(this, 0, sizeof(A)); }
int age;
char type;
};
clear
is intended to clear all members, setting to 0
(byte wise). What could go wrong if we use A
as a base class? There's a subtle source for bugs here.
The compiler is likely to add padding bytes to A. So sizeof(A)
extends beyond char type
(until the end of the padding). However in case of inheritance the compiler might not add the padded bytes. So the call to memset
will overwrite part of the subclass.