The new Operator

As an alternative to malloc, C++ provides the new operator for allocating memory from the free store. The malloc function knows nothing about the type of the variable being allocated; it takes a size as a parameter and returns a void pointer. In contrast, the new operator knows the class of the object you're allocating, and it automatically calls the class's constructor to initialize the memory it allocates. Compare the previous example with the following:

Date *firstPtr, *secondPtr;

int i;

firstPtr = new Date; // Default constructor called

i = firstPtr->getMonth(); // Returns 1 (default value)

secondPtr = new Date( 3, 15, 1985 ); // Constructor called

i = secondPtr->getMonth(); // Returns 3

The new operator calls the appropriate Date constructor, depending on whether you specify arguments or not. This ensures that any objects you allocate are properly constructed.

Also notice the syntax for new. It is not a function, so it doesn't have an argument list in parentheses; it is an operator that you apply to a the name of a type. You don't have to use sizeof to find the size of a Date object, because new can tell what size it is.

The new operator returns a pointer, but you don't have to cast it to a different type when you assign it to a pointer variable. The compiler checks that the type of the pointer matches that of the object being allocated, and generates an error if they don't match. For example:

void *ptr;

ptr = new Date; // Error; type mismatch

If new cannot allocate the memory requested, it returns 0. In C++, a null pointer has the value 0 instead of the value NULL.