Wednesday 12 October 2011

OVERLOADING NEW AND DELETE OPERATOR


OVERLOADING NEW AND DELETE OPERATOR

AIM:
To write a C++ program to implement the overloading of new and delete operators to provide dynamic allocation of memory

ALGORITHM:

Step 1: Start the program.
Step 2: Create a class ‘op’;
Step 3: Declare the overloaded member functions new & delete.
Step 4: Invoke the base class constructor and passing arguments for the new function.
Step 5: The inbuilt identifiers __FILE__ and __LINE__ will get the current file which under processing and the line which currently executing the __LINE__ will be passed.
Step 6: Using malloc the memory will be allocated for the current processing file.
Step 7: Invoke the overloaded operated function delete and pass the pointer variable free the memory which is already allocated.
Step 8: Stop the program.

PROGRAM:

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
class op
{
public:
            void *operator new(size_t size, char const *file,int line);
            void operator delete(void *p);
};
void *op::operator new(size_t size, char const *file,int line)
{
 void *p = malloc(size);
 cout<<"\n New called the file:"<<file<<"\n line:"<<line<<"\n size:"<<size<<"\n p:"<<p<<endl;
 return p;
 }
void op::operator delete(void *p)
{
 cout<<"\n Delete called p:"<<p<<endl;
 free(p);
 }
void main()
{
clrscr();
op *X = new(__FILE__,__LINE__)op;
delete X;
getch();
}

OUTPUT:

 New called the file:NEWDEL1.CPP
 line:24
 size:1
 p:0x8fba0df6
 Delete called p:0x8fba0df6

RESULT:
Thus the C++ program to implement the overloading of new and delete operators to provide dynamic allocation of memory was executed.

0 comments:

Post a Comment