Saturday, May 31, 2008

C++ new and delete

1 comment
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;
}

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;
}

OUTPUT:
Object Created
Object Destroyed
If You Enjoyed This, Take 5 Seconds To Share It

1 comment:

  1. When i merge the above two MyClass, I see that the "In Constructor" is printed twice on MyClass initialization. Not sure why ..

    ReplyDelete