How is dynamic memory management handled in C++?
- C++ supports the operators new and delete for dynamic memory management.
- These operators perform both allocation/ deallocation of memory and initialization/ cleanup of objects.
- The class constructor is automatically called when the object is created and the destructor is called when the object is destroyed.
- The new and delete operators can be overloaded if required.
EXAMPLE: Basic usage of new and delete
#include <iostream> using namespace std; class MyClass { public: MyClass() { cout << "In Constructor" << endl; } ~MyClass() { cout << "In Destructor" << endl; } }; int main() { // Create a delete a single object in heap MyClass* obj = new MyClass(); delete obj; // Create and Delete an array of objects in heap int *intPtr = new int[10]; delete[] intPtr; return 0; }
EXAMPLE: Overloading of new and delete
#include <iostream> using namespace std; class MyClass { public: // Overloaded new void* operator new (size_t sz) { cout << "Object Created" << endl; // Invoke the default new operator return ::new MyClass(); } // Overloaded delete void operator delete(void* ptr) { cout << "Object Destroyed" << endl; // Invoke the default delete operator ::delete ptr; } }; int main() { MyClass* obj = new MyClass(); delete obj; return 0; }OUTPUT:
Object Created Object Destroyed
0 comments:
Post a Comment