class X { int i; int j; public: X(void); ~X(void); }; X::X(void) { i = j = 0; } X::~X(void) { cout << "X destructor is called" << endl; }
This class definition is hardly exciting. However, it serves its
purpose to illustrate the differences between malloc
and
new
.
First, let us consider the following code using malloc
to create an object of
class X
:
X *myX; myX = (X*)malloc(sizeof(X));
Next, let us consider the ``equivalent'' code to create an object
of class X
, but this time using new
:
X *myY; myY = new X;
Now, what is different about that myX
points to, and what myY
points to?
The difference is that the data members of what myX
points to is
not initialized. However, the data members, i
and
j
of what myY
points to are initialized to 0.
In other words, malloc
simply allocates enough memory from
the heap, and returns a pointer. However, new
allocates memory like
malloc
, but it also invokes the default constructor
X::X(void)
.
This is one important difference between malloc
and new
.