Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

What is difference between instantiating a C++ object using new vs. without new?


1 Answer
Samual Sam

In C++, we can instantiate the class object with or without using the new keyword. If the new keyword is not use, then it is like normal object. This will be stored at the stack section. This will be destroyed when the scope ends. But for the case when we want to allocate the space for the item dynamically, then we can create pointer of that class, and instantiate using new operator.

In C++, the new is used to dynamically allocate memory.

Example

#include <iostream>
using namespace std;
class Point {
   int x, y, z;
   public:
      Point(int x, int y, int z) {
         this->x = x;
         this->y = y;
         this->z = z;
      }
      void display() {
         cout << "(" << x << ", " << y << ", " << z << ")" << endl;
      }
};
int main() {
   Point p1(10, 15, 20);
   p1.display();
   Point *ptr;
   ptr = new Point(50, 60, 70);
   ptr->display();
}

Output

(10, 15, 20)
(50, 60, 70)

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.