Saturday 17 September 2011

Overloading using new and delete operator


Overloading using new and delete operator
Aim:
To write a C++ program to overload new and delete operators.
Algorithm:
Step1: Declare the class as Vector.
Step 2: Declare the data member as *array;
Step 3: Declare the member function as
void *operator new(int size)
void operator delete(void * x)
void read()
void sum()
Step 4: In the main, create the object for the Vector class.
Step 5: Allocate the memory space for the array elements using new operator.
Step 6: Read function is used to get the array elements.
Step 7: Add the elements in the array using for loop in the sum function and display the
result.
Step 8: Delete the memory space by delete operator.
Program:
#include <iostream.h>
#include <stdlib.h>
#include <conio.h>
const int ARRAY_SIZE=10;
class vector
{
private:
int *array;
public:
void*  operator new(size_t size)
{
vector *my_vector1;
my_vector1 = :: new vector;
my_vector1->array=new int[size];
return my_vector1;
}

void  operator delete(void* x)
{
vector *my_vector2;
my_vector2 = (vector*)x;
delete(int*)my_vector2->array;
::delete x;
}
void read();
int sum();

};

void vector::read()
{
for(int i=0;i<ARRAY_SIZE;i++)
{
cout<<"Vector["<<i<<"]=?";
cin>>array[i];
}
}
int vector::sum()
{
int sum=0;
for(int i=0;i<ARRAY_SIZE;i++)
sum+=array[i];
return sum;
}

void main()
{
clrscr();
vector *my_vectorP=new vector;
cout<<"Enter Vector data..."<<endl;
my_vectorP->read();
cout<<"The Sum of Vector Elements: "<<my_vectorP->sum();
delete my_vectorP;
getch();
}

Output:

Enter Vector data...
Vector[0]=?1
Vector[1]=?5
Vector[2]=?8
Vector[3]=?7
Vector[4]=?4
Vector[5]=?6
Vector[6]=?1
Vector[7]=?8
Vector[8]=?9
Vector[9]=?10
The sum is 59

0 comments:

Post a Comment