Page 249 - DCAP404 _Object Oriented Programming
P. 249
Object-oriented Programming
Notes This is will allocate memory for an int(eger) having initial value 10, pointed by the ptr pointer.
Memory space for arrays is allocated as shown below:
ptr=new DataType [x];
Here,
1. ptr and DataType have the same meaning as above.
2. x is the number of elements and C is a constant.
Example:
//Example Program in C++
#include<iostream.h>
void main(void)
{
int *ptr, size;
cin>>size;
ptr=new int[size];
//arrays are freed-up like this
delete []ptr;
}
11.5.1 New and Delete Operator
Until now, in all our programs, we have only had as much memory available as we declared for
our variables, having the size of all of them to be determined in the source code, before the
execution of the program. But, what if we need a variable amount of memory that can only be
determined during runtime? For example, in the case that we need some user input to determine
the necessary amount of memory space.
The answer is dynamic memory, for which C++ integrates the operators new and delete.
Operators new and new[]
In order to request dynamic memory we use the operator new. New is followed by a data type
specifier and – if a sequence of more than one element is required – the number of these within
brackets []. It returns a pointer to the beginning of the new block of memory allocated. Its form
is:
pointer = new type
pointer = new type [number_of_elements]
242 LOVELY PROFESSIONAL UNIVERSITY