×

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

C++ String Concatenation

C++ String Concatenation In this section, we will learn about C ++ String Concatenation, what it does, how it works, and will also see its programs. What is the String Concatenation? The + operator...

3 minutes read.

How is multiset implemented in C++

Similar to sets, multisets are an associative container type where several items may share the same values. Associative containers implement instantly searchable sorted data structures with O(log n) complexity. In a multiset,...

5 minutes read.

gmtime() function in C/C++

C++ language is used to make high-performance applications that can work efficiently. It is one of the world's most popular languages. It is an object-oriented and high-level programming language, which...

4 minutes read.

How to build a program in C++

Building a program is all about creating the program and executing it successfully. There are some steps  precisely, which must be followed to make the program. Step 1: Get an IDE...

4 minutes read.

How to declare a 2D array dynamically in C++

In this article, we will learn how to declare the dynamic array in C++. We also learn the initialization of a 2D array using a pointer in C++. Here, we...

3 minutes read.

Programs to Print Pyramid Patterns in C++

We will explore how to use code to print a variety of patterns utilizing stars (*), numbers (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,.…)  and alphabets...

7 minutes read.

How to Handle Divide by Zero Exception in C++

If you are a programmer or interested in coding then it is obvious that you face some illogical test cases. Suppose, you have written one program that calculates the factorial...

6 minutes read.

Factorial of a Number in C++ using while Loop

What is a factorial? The factorial of a number is the product of all the positive numbers less than or equal to n, indicated by n! According to the standard for an...

6 minutes read.

Assertions in C/C++

Assertions are the statements used to check presumptions which is made by the programmers. Example: Assertion is used to verify whether the malloc returned by the pointer is NULL or not. For...

4 minutes read.

C++ String

A string is a collection of characters. C++ programming language supports both C string as well as standard C++ library string. In C++, string is an object of std::string class. C Style String The C style...

5 minutes read.

Message Passing in C++

The act of sending and receiving information by an object is referred to as communication, and all communication between objects that takes place via message is known as message passing....

1 minute read.

Hexadecimal to Decimal in C++

In computers, hexadecimal numbers are represented with base 16 and decimal numbers are represented with base 10 and values 0-9, whereas hexadecimal numbers have digits ranging from 0 to 15,...

3 minutes read.

How the value is passed in C++

Introduction: The call-by-value method of giving arguments to a function duplicates the real value of an argument into the formal parameter of the function. In this instance, modifications to the parameter...

5 minutes read.

C++ Global Variable

In C++, a global variable is a variable that is defined outside of any function or class and can be accessed by any function or class in the program. Global...

4 minutes read.

Program to convert infix to postfix expression in C++

Parentheses are frequently employed in mathematical formulas to make their interpretation easier to understand. However, with computers, parenthesis in an expression might lengthen the time it takes to find a...

7 minutes read.

How to implement map in C++

Part of the C++ STL is maps (Standard Template Library). Maps are associative containers that hold sorted key-value pairs, where each key is distinct and may only be added or...

4 minutes read.

C++ Switch

In C++, an expression or variable can be tested against a range of constant values using a switch statement, which is a control flow statement. It offers a productive method...

4 minutes read.

C++ Math Functions

C++ Math Functions: Like other programming languages, C++ offers plenty of mathematical functions needed for various purposes. These functions are defined mainly in the math library in C++. Let us...

4 minutes read.

C++ Continue in for loop

Continue statement: Inside the loop, the continue statement is used to control the loop. C++ utilizes the continue keyword to implement the continue statement, which transfers the program's flow at the start...

4 minutes read.

Inheritance Program in C++

What is Inheritance? Inheritance is the ability of a class to inherit traits and properties from another class. One of the most crucial aspects of Object-Oriented Programming is inheritance. The ability or...

9 minutes read.