Memory
Management Operators in C++:
To allocate memory, C++ supports two unary operators new and delete. These operators allocate and deallocate the memory in
better and easy way.
·
Advantages of new operator over
malloc function:
i.
It automatically computes the size
of data object. We need not use the operator sizeof();
ii.
It automatically returns the
current pointer type so there is no need to type cast.
iii.
Like any other operator new and delete can be overloaded.
iv.
It is possible to initialize the
object while allocating the memory.
Syntax for “new”:
Data
type pointer_variable = new data
type;
Ex:
int
*p = new int;
OR
int *p;
*p = new int;
Note:
We can also initialize the memory using new
operator.
Pointer_variable
= new data type (value);
Ex:
int *p = new int (0);
Note:
We can also allocate memory space to array.
Pointer_variable
= new data type [size];
Ex:
int *p = new int[5];
0 comments:
Post a Comment