Home » C++ programs

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



In this program, we are going to learn about new and delete operators in C++ programming language, and testing the case of calling constructor and destructors while allocating and deal locating the memory dynamically.
Submitted by IncludeHelp, on May 22, 2018

In C++ programming language, there are two operators 1) new and 2) delete, which are used to manage the memory dynamically i.e. to create, delete the memory at run time (dynamically)

Prerequisite: new and delete operators in C++ programming

Let’s understand, when 'new' and 'delete' are used?

new is used to declare memory blocks at run time (dynamically). While, delete is used to delete/free the memory which has been declared dynamically.

Example of new and delete in C++

In the given program, we are using new to allocate memory to the class object and delete/free is using to delete the reference of the pointer that will force. There is a class named sample and it has a constructor sample() and a destructor ~sample().

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".






Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions





© https://www.includehelp.com (2015-2018), Some rights reserved.




close Like other websites, this site uses cookies to deliver relevant ads based on your interest, by using our website, you acknowledge that you have read our privacy policy.