What are the differences between new and malloc?
Here are some of the differences between new and malloc:
- Objects created with new will have constructors and destructors called automatically, whereas malloc doesn't know anything about the constructors and destructors of the objects, so the initialization and destruction of objects will have to be done manually.
- new returns pointer of the right type, where as malloc returns pointer of type void*, which is not type-safe.
- new operator can be overridden, whereas malloc cannot be overridden(on per class basis).
- While allocating with malloc, we need to specify the size of memory to be allocated explicitly(using sizeof). Where as new implicitly obtains the sizeof of the object to be allocated.
- Memory allocated with malloc can be reallocated with a new size using realloc, but there is no such feature for objects created with new.