What is the output of the following C++ program?
[gamipress_button type=”submit” label=”Run Code Online” onclick=”window.open(‘https://coderseditor.com’,’_blank’)”]
#include<stdlib.h> #include<iostream> using namespace std; class Test { public: void* operator new(size_t size); void operator delete(void*); Test() { cout<<"\n Constructor called"; } ~Test() { cout<<"\n Destructor called"; } }; void* Test::operator new(size_t size) { cout<<"\n new called"; void *storage = malloc(size); return storage; } void Test::operator delete(void *p ) { cout<<"\n delete called"; free(p); } int main() { Test *m = new Test(); delete m; return 0; }
Studently Answered question October 10, 2022
Output
new called
Constructor called
Destructor called
delete called
Dynamically allocating memory using the new keyword does two things:
Allocating memory and calling constructors. Memory allocation is done using operator new. The program above has a user-defined operator new , so first the user-defined operator new is called and then the constructor is called.
The destruction process is the reverse. First the destructor is called, then the memory is freed.
Studently Answered question October 10, 2022