Wednesday, January 10, 2007

Virtual Function and ZeroMemory

What caused me to write this post is a BUG. Really i am not joking.. Everyone know that there is a virtual table pointer is present at the  beginning of the object memory . i am also know that.. But i did a mistake long ago. Following lines shows it...

class Base
{

public :
   virtual void Render()
   {
   }

};

class Derived: public Base
{

    // i have several data members here..

public :

    Derived()
    {

        // For easily initializing all of my data members to zero , i used ZeroMemory here

       ZeroMemory(this,sizeof(Derived));
       // Danger .. This also clear the virtual table pointer..
    }

   void Render()
   {
   }

};


So when i called it like 

Derived *d = new Derived()
d->Render();

it crasheddd .... because of the ZeroMemory in the constructor set the vptr to Zero.

No comments: