Ad Code

Responsive Advertisement

Write a C++ program that overload new and delete operator.










// CPP program to demonstrate  
// Overloading new and delete operator  
// for a specific class 
#include <iostream>
#include <stdlib.h>
  
using namespace std; 
class student 
{ 
    string name; 
    int age; 
public: 
    student() 
    { 
        cout<< "Constructor is called\n" ;  
    } 
    student(string name, int age) 
    { 
        this->name = name; 
        this->age = age; 
    } 
    void display() 
    { 
        cout<< "Name:" << name << endl; 
        cout<< "Age:" << age << endl; 
    } 
    void * operator new(size_t size) 
    { 
        cout<< "Overloading new operator with size: " << size << endl; 
        void * p = ::new student();  
        //void * p = malloc(size); will also work fine 
      
        return p; 
    } 
  
    void operator delete(void * p) 
    { 
        cout<< "Overloading delete operator " << endl; 
        free(p); 
    } 
}; 
  
int main() 
{ 
    student * p = new student("Yash", 24); 
  
    p->display(); 
    delete p; 
}

out put:
 Overloading new operator with size: 16
Constructor is called
Name:Yash
Age:24
Overloading delete operator 



If you like code with vibhu  and would like to contribute, you can also write an article using   This link :

https://docs.google.com/forms/d/e/1FAIpQLScAmvlPvNUz35R-G0nc_zpRVP3o8xlhtFgC3aKPyLetX_RyXg/viewform?pli=1


OR  mail your article to codewithvibhu@gmail.com.  See your article appearing on the code with vibhu main page and help other students. 

Post a Comment

0 Comments