Experiment 4
Aim
To overload the new and delete operators to provide
custom dynamic allocation and deallocation of memory.
Objectives
- To
understand dynamic memory allocation.
- To
understand operator overloading for memory management.
- To
implement class-specific new and delete.
- To
observe custom memory allocation and deallocation.
Theory
The new operator allocates memory and invokes the
constructor, whereas delete releases memory and invokes the destructor.
C++ allows these operators to be overloaded for a class to
provide custom memory management.
Program
#include <iostream>
#include <cstdlib>
using namespace std;
class Demo {
int value;
public:
Demo(int v = 0) {
value = v;
cout <<
"Constructor called\n";
}
void show() {
cout <<
"Value = " << value << endl;
}
void* operator
new(size_t size) {
cout <<
"Custom new called\n";
return
malloc(size);
}
void operator
delete(void *p) {
cout <<
"Custom delete called\n";
free(p);
}
};
int main() {
Demo *p = new
Demo(100);
p->show();
delete p;
return 0;
}
Result
Thus, the new and delete operators were successfully
overloaded to provide custom memory allocation and deallocation.
No comments:
Post a Comment