Bloomberg LP Interview Question
Financial Software DevelopersIt's common practice in C, to do a memset on structures, in order to initialize all member variables to some default value, usually NULL. Similarly, you can use memset to initialize class objects. But what happens if the class contains some virtual functions?
Let's take an example:
class GraphicsObject{
protected:
char *m_pcName;
int m_iId;
//etc
public:
virtual void Draw() {}
virtual int Area() {}
char* Name() { return m_pcName;}
};
class Circle: public GraphicsObject{
void Draw() { /*draw something*/ }
int Area() { /*calculate Area*/ }
};
void main()
{
GraphicsObject *obj = new Circle; //Create an object
memset((void *)obj,NULL,sizeof(Circle)); //memset to 0
obj->Name(); //Non virtual function call works fine
obj->Draw(); //Crashes here
}
This results in a crash, because every object of a class containing virtual functions contains a pointer to the virtual function table(vtbl). 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.
Static functions will work since they do not access data members.
About virtual functions. If a virtual function is called through the object's name (not a pointer or reference to the object) compilers can easily optimize this call so that the virtual table will not be used in run-time. Nevertheless, the behavior is undefined.
I think your answer is correct and good enough.
- Vivi April 05, 2010