
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
When to Use new Operator in C++
Use of the new operator signifies a request for the memory allocation on the heap. If the sufficient memory is available, it initializes the memory and returns its address to the pointer variable.
The new operator should only be used if the data object should remain in memory until delete is called. Otherwise if the new operator is not used, the object is automatically destroyed when it goes out of scope. In other words, the objects using new are cleaned up manually while other objects are automatically cleaned when they go out of scope.
The following is the syntax of new operator.
pointer_variable = new datatype;
In the above syntax, pointer_variable is pointer variable to whom the memory address is returned and datatype is the build-in data type for the memory.
A program that demonstrates the use of new operator is given as follows.
Example
#include <iostream> using namespace std; int main () { int *ptr1 = NULL; ptr1 = new int; float *ptr2 = new float(223.324); *ptr1 = 28; cout << "Value of pointer variable 1 : " << *ptr1 << endl; cout << "Value of pointer variable 2 : " << *ptr2 << endl; delete ptr1; delete ptr2; return 0; }
Output
The output of the above program is as follows.
Value of pointer variable 1 : 28 Value of pointer variable 2 : 223.324
Now let us understand the above program.
The new operator is used to initialize the memory and return its address to the pointer variable ptr1 and ptr2. Then the values stored at memory positions pointed to by ptr1 and ptr2 are displayed. Finally the delete operator is used to free the memory.
The code snippet that shows this is as follows −
int *ptr1 = NULL; ptr1 = new int; float *ptr2 = new float(223.324); *ptr1 = 28; cout << "Value of pointer variable 1 : " << *ptr1 << endl; cout << "Value of pointer variable 2 : " << *ptr2 << endl; delete ptr1; delete ptr2;