×

New Operator in C++

Dynamic memory allocation in C++ means manually allocating the memory by the developer duing run-time. The dynamic memory is allocated in the heap section of the RAM, whereas the static memory is allocated in the stack section. Therefore, during dynamic allocation, data is stored in the heap data structure in the RAM. This process of dynamic allocation is done using the new operator. This new operator can be used for predefined and custom data types. These kinds of dynamically allocated constructors are used to reduce memory usage.

Syntax

The syntax for a new operator in C++

pointer_variable_of_data_type = new data type;

Examples for using a new operator:

int *ptr = NULL;
 ptr = new int();

Here, the pointer is declared with variable ptr, and we have assigned null to the variable. We can pass the parameters in the int().

We can use the new operator to use in the array, such as:

int* myarray = NULL;
myarray = new int[10];

Example:1

#include <iostream>
using namespace std;


int main() {


  // declare an int pointer
  int* pointInt;


  // declare a float pointer
  float* pointFloat;


  // dynamically allocate memory
  pointInt = new int;
  pointFloat = new float;


  // assigning value to the memory
  *pointInt = 39;
  *pointFloat = 69.45f;


  cout << *pointInt << endl;
  cout << *pointFloat << endl;


  // deallocate the memory
  delete pointInt;
  delete pointFloat;


  return 0;
}

Output:

New Operator in C++

Explanation:

In this code, we have declared two pointers in the main function in the above example. These are pointInt, which stores the integer value, and pointFloat to store the float value in the same function. We have used a new statement for the above two variables and then passed two values for the variables. Then we printed the two variables using the cout statement.

Example:2 Using new statement for arrays:

#include <iostream>
using namespace std;


int main() {


  int num;
  cout << "Enter total number of students: ";
  cin >> num;
  float* ptr;


  // memory allocation of num number of floats
  ptr = new float[num];


  cout << "Enter GPA of students." << endl;
  for (int i = 0; i < num; ++i) {
    cout << "Student" << i + 1 << ": ";
    cin >> *(ptr + i);
  }


  cout << "\nShowing GPA of students." << endl;
  for (int i = 0; i < num; ++i) {
    cout << "Student" << i + 1 << ": " << *(ptr + i) << endl;
  }


  // ptr memory is released
  delete[] ptr;


  return 0;
}

Output:

New Operator in C++

Explanation:

We have created an array using a new statement in the above example. Using for loop, we have entered the values in the array, and then we printed the values in the array using the cout statement. At last, we have used the delete statement, which is used to deallocate memory dynamically.

Example:3

#include <iostream>
using namespace std;


class Student {
  string name;


  public:


    Student() {
      // Constructor
      cout << "Greeting from constructor";
    }
};


int main() {
  // creating student object using the new keyword
  Student * student = new Student();


  return 0;


}

Output:

New Operator in C++

Explanation:

In the above code, we have created a class Student inside which we have declared a constructor with the same name as the class. Inside the class, we have declared a written cout statement. In the main function, we created an object for the class using the new statement.

Example: 4

#include<iostream>
using namespace std;


class example
{
  int num1;
  int num2;
  int *ptr;


public:
  // default constructor (here, it is a dynamic constructor also)
  example()
  {
    num1 = 0;
    num2 = 0;
    ptr = new int;
  }


  //dynamic constructor with parameters
  example(int x, int y, int z)
  {
    num1 = x;
    num2 = y;


    ptr = new int;
    *ptr = z;
  }


 void display()
 {
   cout << num1 << " " << num2 << " " << *ptr;
 }
};


int main()
{
  example obj1;
  example obj2(20, 50, 1);


  obj1.display();
  cout << endl;


  obj2.display();
}

Output:

New Operator in C++

Explanation:

We used the dynamic constructor in the above example and passed a few arguments. Similarly, as in the previous example, we have created a variable with a new statement. Unlike in the previous example, we have passed a few arguments


Related Topics

Boost split in C++ library

Boost::split in C++ library Boost offers strong tools for adding mature, well-tested libraries to the C++ standard library. The boost: split function, which is a component of the Boost string algorithm...

2 minutes read.

How to create the Processes with Fork in C++

 In this article, we are going to explain the different methods that help us to create processes with a fork(). There are two methods to do so. These methods are...

2 minutes read.

Upcasting and Downcasting in C++

With the help of various examples in the C++ programming language, this section will cover Upcasting and Downcasting. Upcasting and downcasting, on the other hand, are two forms of object typecasting. Consider...

3 minutes read.

Nullptr in C++

What is Nullptr in C++? A null pointer value is represented by the term nullptr. Use a null pointer value to indicate that a native pointer type, inner pointer, or object...

3 minutes read.

Default Constructor

C++ Default Constructor A default constructor is such constructor which does not take any parameter. A constructor initializes the data member when a class object created. If a programmer does not create any...

2 minutes read.

Timsort Implementation Using C++

Timsort Implementation Using C++ The Timsort is a stable sorting algorithm that uses the idea of merge sort and insertion sort. It can also be called a hybrid algorithm of insertion...

3 minutes read.

C++ Program to Print Fibonacci Triangle

Fibonacci Triangle Program in CPP Definition: Fibonacci Triangle as the name suggests is the same as the Fibonacci number series where the next element is the sum of the previous two elements....

3 minutes read.

Tensorflow in C++

With cppflow, you can execute TensorFlow models in C++ without Bazel, TensorFlow installation, or TensorFlow compilation. Tensor manipulation, eager execution, and running stored models straight from C++ are all possible. Knowing...

7 minutes read.

Constructor Overloading in C++

A Constructor is a class member function that is used to initialize the class's objects. Constructors have no return type and are called automatically when an object is formed. Constructor Characteristics Constructors...

3 minutes read.

C++ Program to Implement Merge Sort

C++ Program to Implement Merge Sort The technique of merge sort is based on the strategy of divide and conquer. We divide the set of while data into smaller bits, arranged...

3 minutes read.

Loops in C++

A loop statement in most programming languages allows us to execute a statement or a collection of statements numerous times. Control structures of programming languages vary, allowing for more complex...

6 minutes read.

Parameterize Constructor

C++ Parameterized Constructor A constructor having parameters is known as parameterize constructor. Parameterize constructor is used to assign different values. Syntax: className(data-type argument){   // Constructor definition   }   className(data-type argument, data-type argument){   // Constructor definition   } A parameterized constructor can be passed values to constructor function in two ways: 1)...

1 minute read.

Diamond Pattern in C++ using For Loop

For Loop: A for loop is a repetitive control structure that allows you to create a loop for executing a specific number of times. The syntax of for loop: In C++, a for...

5 minutes read.

Virtual base class in C++

Consider in a C++ program, there are 4 classes named class A, class B, class C, and class D. If class B and class c inherit properties from class A....

3 minutes read.

C++ Program to find largest subarray with 0 sum

Write a program to find the largest subarray that has a sum zero. The array contains positive and negative numbers. Print the length of the max subarray whose sum turns...

4 minutes read.

C++ STL Components

C++ STL Components In today’s article, we are going to learn about all the points things that is related to STL in C++ so stay connected because you are going to...

6 minutes read.

Advanced C++ with Boost Library

The goal of the Boost Libraries is to be widely applicable and used in a variety of applications. For instance, they can in handy when working with huge numbers whose...

4 minutes read.

How to create a button in C++

A button is an option through which a user can control to click a provided input to an application. There are several buttons, each with different styles, to maintain the...

3 minutes read.

Reverse String Word-Wise in C++

What is a reversed String? Reversing the words of a sentence is called reversed string by words. The difference between the reverse a string and the reverse a string word-wise is...

4 minutes read.

Learn C++ Tutorial

C++ Introduction C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at AT&T Bell Laboratories. It is superset (extension) of C programming language. Depending upon features supported by programming...

10 minutes read.