Home »
C++ Quiz Questions
C++ | new and delete operators | question 4
What is the output of the following program?
#include <iostream>
using namespace std;
class sample
{
public:
sample()
{
cout<<"Hi ";
}
~sample()
{
cout<<"Bye ";
}
};
int main()
{
sample *obj = new sample();
delete(obj);
return 0;
}
(1) Hi Bye
(2) Hi
(3) Bye
(4) No outpyt
Answer: (1)
Explanation:
In C++ programming language, operator new is used to create memory at run time (dynamically memory allocation) and delete is used to free/delete dynamically allocated memory.
new calls the constructor and delete calls the destructor.
In this program, sample() is a constrictor which is printing "Hi" and ~sample() is a destructor which is printing "Bye".
Since, we have used both of the statement in the program 1) new operator and 2) delete operator. Therefore, constructor and destructor both will be called and they will print "Hi" and "Bye". Thus, the output will be "Hi Bye".