Saturday, May 31, 2008

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.

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

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

5 comments :

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

    ReplyDelete
    Replies
    1. you have overloaded the new operator, so new's function remains the same, i.e. call the constructor.

      Delete
  2. in the definition of operator new(),how it is working "::new MyClass()".how it will invoke default new.

    ReplyDelete
  3. overloaded new operator return type is void*
    void* operator new (size_t sz) {}

    and
    MyClass* obj = new MyClass();

    how it got typecasted.

    ReplyDelete
  4. wow, If i know this site before 20 days, I'll get 5 marks in my c++ examination.

    ReplyDelete

Contact Form

Name

Email *

Message *

Back to Top