ASK Question

Quick links:
Latest articles
Internship
Members

Languages:
C
C++
C++ STL
Java
Data Structure
C#.Net
Android
Kotlin
SQL

Web:
PHP
Python
JavaScript
CSS
Ajax
Node.js
Web prog.

Programs:
C
C++
DS
Java
C#
Python


Aptitude:
C
C++
Java
DBMS

Interview:
C
Embedded C
Java
SEO
HR

CS Subjects:
CS Basics
O.S.
Networks
DBMS
Embedded Systems
Cloud Computing
Machine learning
CS Organizations
Linux
DOS

More:
Articles
Puzzles
News/Updates


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






Quick links:
C FAQ(s) C Advance programs C/C++ Tips & Tricks Puzzles JavaScript CSS Python Linux Commands PHP Android Articles More...

Was this page helpful? Please share with your friends...

Are you a blogger? Join our Blogging forum.

Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


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