The memory allocation operator new and delete can be overloaded to handle memory resource in a customized way.
An application designed to handle memory allocation by itself through overloading can easily detect memory leaks.
//Overloading of new and delete operators #include<iostream.h> Const int ARRAY-SIZE = 10; class vector { int*array; //array is dynamically allocatable data member public: //overloading of new operator void*operator new (sizetsize) { vector*my_vector; my_vector=::new vector; //it refers to global //new, otherwise leads to recursive //call of vector::new my_vector → array = new int [ARRAY-SIZE]; return my_vector; } //Overloading of delete operator void operator delete (void*Vec) { vector*my_vect; my_vect=(vector*)vec; delete (int*)my_vect→array; //calls::delete //otherwise leads to recursive, //call of vector :: delete } void read() { for (int i=0; i<ARRAY - SIZE; i++> { cout<<"vector["<<i<<"]=?"; cin>>array[i]; } } int sum() { int sum=0; for (int i=0; i<ARRAY-SIZE; i++> Sum=array [i]; return sum; } }; void main() { vector*my:vector=new vector; cout<<"Enter vector data"<<end/; my:vector→read(); cout<<"Sum of vector ="<<my:vector→Sum(); delete my:vector; }
Output
Enter vector data
vector[0] = ? 1
vector[1] = ? 2
vector[2] = ? 3
vector[3] = ? 4
vector[4] = ? 5
vector[5] = ? 6
vector[6] = ? 7
vector[7] = ? 8
vector[8] = ? 9
vector[9] = ? 10
Sum of Vector = 55
In the above program, in new function the statement,
my:vector=::new vector
Creates an object of the vector class. If scope resolution operator is not used, the overloaded operator function is called recursively leading to stack overflow.
Hence, prefixing of the scape resolution operator to the operator forces to use the standard new operator supported by the language instead of the one defined in the program.
my:vector → array = new int (ARRAY-SIZE); creates an array and dynamically allocates memory to it.
Similarly the delete operator is overloaded.
Read More Topics |
Linked list dynamic memory allocation |
Operating system components |
Abstract class in C++ |