Sobes.tech
Junior — Middle

Can you explain how the 'new' operator works when creating objects in programming languages?

sobes.tech AI

Answer from AI

The new operator in C++ allocates memory for an object in the dynamic area (heap) and returns a pointer to this memory. It also calls the object's constructor for initialization.

Example:

int* p = new int(5); // allocates memory for int and initializes it with the value 5

class MyClass {
public:
    MyClass() { /* initialization */ }
};

MyClass* obj = new MyClass(); // allocates memory and calls the constructor

Important: The new operator in C++ is different from the new operator in C, which simply allocates memory without calling constructors. In C++, new combines memory allocation and object initialization.