Q:

new and delete operators in C++ with printing values through constructor and destructor

belongs to collection: C++ programs on various topics

0

new and delete operators in C++ with printing values through constructor and destructor

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Consider the 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;
}

Output

    Hi Bye 

You can see, "Hi" is written in the constructor (sample()) while "Bye" is written in the destructor (~sample()).

 

Therefore, when object "obj" is creating, constructor will be called and print "Hi", same as when object is going to be freed using delete(obj), destructor (~sample()) will be called and print "Bye".

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ programs on various topics

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C++ program to generate random password... >>
<< C++ program to declare an integer variable dynamic...