Which is called first constructor or overloaded new operator in C++?

(Last Updated On: March 17, 2018)

Interview Question: A C++ class has constructor and overloaded new and delete operator function. If we create a class object dynamically using new then out of constructor and overloaded new operator function, which one get called first?

Recommended to read a simple program with important important points of new and delete operator overloading in C++

Answer: if we have overloaded new operator in the class then on creation of object dynamically, overloaded new operator will be called first and then class constructor will be called.

And reverse is the case for overloaded delete and destructor i.e. destructor will be called first then overloaded delete operator in C++ program

Below is the C++ program illustrating overloading of new and delete operators. In this program, we have a class Book and this class has constructor Book(), overloaded new and delete operator and a destructor ~Book().

On creation of object of Book class in main () function, first overloaded new function will be called then the class constructor.

 

 

OUTPUT:

Overloaded new operator
constructor
Destructor
overloaded delete operator

NOTE
If we overload new and delete operator in a class, then on creation of object using new, memory will not be directly requested from operating system, but class new and delete overloaded function will be called in which we write custom memory allocation or request memory to operating system.