How can we initialize data members to some default values??

So many options are available now. right?

ZeroMemory(), memset() etc are there..

Using ZeroMemory() memory management function , we can fills a block of memory with zeros. 

For example 

char szSendURL[256];

ZeroMemory(szSendURL,sizeof(szSendURL));

🙂

 

Then we move to the next one. memset()..

Using memset() we can Sets buffers to a specified character.

For example 

 

char buffer[4];

memset( buffer, ‘*’, 4 );

Similarly, you can use memset() to initialize class objects also. 😀

But what happens if the class contains some virtual functions? *-)

Let’s take another example

#include <string.h>
#include <memory.h>
#include <iostream.h>
class Bird
{
protected:
char m_Name[25];
public:
virtual void SetName() {}
char* ShowName() { return m_Name;}
};

class Flying_Bird: public Bird
{
void SetName() { strcpy(m_Name,”Dove”); }
};

void main()
{
Bird *obj = new Flying_Bird(); //Create an object
memset((void *)obj,NULL,sizeof(Flying_Bird)); //memset to 0
obj->SetName(); //Crashes here
cout<<obj->ShowName();
}

 

🙂

This results in a program crash. Because one virtual function is there. Also that contains one pointer to the virtual function table (VTABLE) also. This pointer is used to resolve virtual function calls, at run time and for dynamic type casting. The pointer is hidden, and is not accessible to programmers by normal means. When we do a memset(), the value of this pointer also gets overwritten, which, in turn, results in a crash, if a virtual function is called.

To avoid such mysterious crashes, memset() should not be used on the objects of a class with virtual functions. Instead use the default constructor or an init routine to initialize member variables.

🙂

“Life never leaves u empty, it always replace everything u lost”

for https://vctipsplusplus.wordpress.com/

BijU

Advertisements