Overloading new and delete operator – Custom Dynamic Memory Allocation


//Overloading new and delete operator using malloc and free

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
class vector
{
private:
int *array;
public:
void *operator new(size_t size)
{
void *v;
cout<<“\nOperator new invoked…”;
v=malloc(size);
if(!v)
{
cout<<“Unable to allocate memory”;
exit(0);
}
return v;
}

void operator delete(void* v)
{
cout<<“\nOperator delete invoked…”;
free (v);
}
void read(int);
int max(int);
int sum(int);
};

void vector::read(int s)
{
for(int i=0; i<s; i++)
{
cout<<“\nEnter element “<<i+1<<“:”;
cin>>array[i];
}
}

int vector::sum(int s)
{
int tot=0;
for(int i=0; i<s; i++)
tot+=array[i];
return tot;
}

int vector::max(int s)
{
int max=0;
for(int i=0;i<s;i++)
if(array[i]>max)
max = array[i];
return max;
}

void main()
{
int s;
clrscr();
cout<<“\nEnter how many elements…”;
cin >> s;
vector *vec = new vector;
cout<<“Enter vector data…\n”;
vec->read(s);
cout<<“\nThe maximum value is…” <<vec->max(s);
cout<<“\nThe sum is…”<< vec->sum(s);
delete vec;
getch();
}

//Overloading new and delete operator using ::new and ::delete

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>

class vector
{
private:
int *array;
public:
void *operator new(size_t size)
{
vector *v;
cout<<“\nOperator new invoked…”;
v=::new vector;
v->array = new int[size];
if(!v)
{
cout<<“Unable to allocate memory”;
exit(0);
}
return v;
}

void operator delete(void* v)
{
cout<<“\nOperator delete invoked…”;
vector *vp;
vp = (vector*) v;
delete (int *) vp->array;
::delete v;
}
void read(int);
int max(int);
int sum(int);
};

void vector::read(int s)
{
for(int i=0; i<s; i++)
{
cout<<“\nEnter element “<<i+1<<“:”;
cin>>array[i];
}
}

int vector::sum(int s)
{
int tot=0;
for(int i=0; i<s; i++)
tot+=array[i];
return tot;
}

int vector::max(int s)
{
int max=0;
for(int i=0;i<s;i++)
if(array[i]>max)
max = array[i];
return max;
}

void main()
{
int s;
clrscr();
cout<<“\nEnter how many elements…”;
cin >> s;
vector *vec = new vector;
cout<<“Enter vector data…\n”;
vec->read(s);
cout<<“\nThe maximum value is…” <<vec->max(s);
cout<<“\nThe sum is…”<< vec->sum(s);
delete vec;
getch();
}

Advertisements