Do not use malloc, use new - malloc does not call constructors.
When you execute A * a = new A(); , the compiler will allocate memory, set the vtable pointer to A, and invoke the constructor. When you call a virtual function, the virtual table is used to actually search for the function.
When you do A * a = (A *) malloc(...); , the compiler will allocate memory that will contain random data. When you call a virtual function, it will look at the (trash) vtable and call a random location.
A class with virtual functions looks something like this:
struct Foo { void * vtable; int aClassMemberVar; };
A virtual function call looks at the "hidden" vtable pointer, which points to the vtable class, a linked list of function pointers. Therefore, this vtable pointer must be initialized, and malloc does not.
source share