C++ small gotcha - 3

Have two class as below:

 

struct MyBase

{

  __int64 x;

  __int64 y;

  MyBase()

  {

          memset(this, 0, sizeof(MyBase));

  }

};

 

struct MyDerived: public MyBase

{

  int z;

  MyDerived():MyBase(), z(0)

  {}

};

 

Then create two objects as below, and then compare these two
objects with memcmp, do you think the c compare will be equal since the
constructor has initialized all the members of the objects to be 0?

 MyDerived obj1;
 MyDerived obj2;
  
 if (memcmp(&obj1, &obj2, sizeof(MyDerived)) == 0)
 {
         cout << "equal" << endl;
 }

 

The answer is no. Since due to data alignment, the size of
MyDerived is 24 bytes, although the constructor has initialized x, y and z to
0, there are still 4 bytes keeps uninitialized, so they may be equal or not.