FAQ 12.02 Why is new better than good old trustworthy malloc()?
Object construction: In C++, new and delete create and destroy objects. In contrast, malloc() and free() merely allocate and deallocate memory. Safety: The new operator returns a pointer of the correct type whereas the function malloc() returns a void*, which isn't type safe. The C language allows a void* to be converted to any other pointer, but this is a dangerous hole in C's type-checking system. C++ doesn't have this weakness: converting a void* to a different pointer type requires an explicit cast in C++. Flexibility: The new operator can be overloaded by a class. For example, new Fred() can use a different memory allocation primitive than is used by new Wilma(). In contrast, malloc() cannot be overloaded on a class-by-class basis. |