Predict the output?
#include<stdlib.h>
#include<stdio.h>
#include<iostream>
using namespace std;
class Test {
int x;
public:
void* operator new(size_t size);
void operator delete(void*);
Test(int i) {
x = i;
cout << "Constructor called \n";
}
~Test() { cout << "Destructor called \n"; }
};
void* Test::operator new(size_t size)
{
void *storage = malloc(size);
cout << "new called \n";
return storage;
}
void Test::operator delete(void *p )
{
cout<<"delete called \n";
free(p);
}
int main()
{
Test *m = new Test(5);
delete m;
return 0;
}
|
(A) new called
Constructor called
delete called
Destructor called
(B) new called
Constructor called
Destructor called
delete called
(C) Constructor called
new called
Destructor called
delete called
(D) Constructor called
new called
delete called
Destructor called
Answer: (B) Explanation: Consider the following statement
Test *ptr = new Test;
There are actually two things that happen in the above statement–memory allocation and object construction; the
new keyword is responsible for both. One step in the process is to call
operator new in order to allocate memory; the other step is to actually invoke the constructor.
Operator new only allows us to change the memory allocation method, but does not do anything with the constructor calling method.
Keyword new is responsible for calling the constructor, not
operator new.
Quiz of this Question
Last Updated :
28 Jun, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...