Overloaded new and delete operator for arrays

Let us try to understand the overloading of new and delete operator for arrays using below example. #include <iostream>using namespace std;void* operator new(size_t sz) {    cout << “Global Memory Allocation: ” << sz << endl;    void* ptr = malloc(sz);    return ptr;}void operator delete(void* ptr) {    cout << “Global memory Deallocation” << endl;    free(ptr);}class Memory {    enum { mem_size = 10 };    int arr[mem_size];public:    Memory() {        cout << “Memory C’tor” << endl;    } ~Memory() {        cout << “Memory D’tor” << endl;    }    void* operator new(size_t sz) {        cout << “Class Memory…

Overload new and delete operator

new operator allocates the memory then calls the constructor. delete operator calls the destructor then delete the memory. As these are operators, so it can be overloaded. But why we need to overload these operators.* In case, there is lot of allocation and deallocation happens from the heap memory, it can affect the performance. So, to overcome this, we overload the new and delete operator.* Also, as part of above scenario, heap memory gets fragmented. As a result, even though there is sufficient memory present in heap, still it is…

new and delete operator

new operator is used to allocate memory in runtime. This memory is allocated from heap segment of a process. To understand how new operator works, let us see with the help of an example. #include <iostream>using namespace std;class employee {    unsigned short m_age;    unsigned int m_salary;public:    employee() {}    employee(unsigned short age, unsigned int salary) {        m_age = age;        m_salary = salary;    }};int main() {    employee* emp = new employee(30, 40,000);    delete emp;    return 0;} Here new is called for the employee object by passing the value as per the constructor…