Overloading New and Delete Operators





This video tutorial explains how to overload new and delete operators in c++ and change the method of dynamic allocation in c++ programming.

check out more about  malloc and free


You are gonna learn what is the need to overload new and delete, what is the syntax of overloading operator function for new and delete and how to overload new and delete in detail with example.

source code for this tutorial

#include <iostream>
#include <cstdlib>
#include <stdexcept>
using namespace std;

class Student {
string name;
int age;
public:
    Student(){
    name = "noname";
    age = 0;
    }
    Student(string name, int age){
    this-> name = name;
    this->age = age;
    }
    void whoAreYou(){
    cout << "hi my name is "<<name<<" and my age is "<<age<<endl;
    }

    void *operator new(size_t size){
    void *pointer;
    cout << "overloaded new. size is "<<size<<endl;
    pointer = malloc(size);
    if(!pointer){
    bad_alloc ba;
    throw ba;
    }
    return pointer;
    }

    void operator delete(void *pointer){
    cout << "overloaded delete"<<endl;
    free(pointer);
    }

};


int main()
{

Student *anilsptr;
try{
anilsptr = new Student("anil",24);
anilsptr->whoAreYou();
delete anilsptr;
}catch(bad_alloc b){
cout << b.what()<<endl;
}

 return 0;
}

 
Back To Top