Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the `new` operator always call the constructor?

My question is influenced by Prof. Thomas Cormen's second comment on his Quora answer$.

He says that the constructor carries out the following three tasks:

  1. Allocates memory for the object.

  2. Initializes the instance variables of the object, e.g., by implicitly calling init in Python. (I also emphasize that the init method should initialize not some, but all of the instance variables.)

  3. Returns a reference to (i.e., address of) the object.

However, the MSDN documentation for C++* says that it is the new operator that does that:

Allocates memory for an object or array of objects of type-name from the free store and returns a suitably typed, nonzero pointer to the object.

My question is, who is right? Or, is there something more to it, perhaps like the new operator always calls the constructor, as suggested by a comment on the post?

Thanks.

$ Unfortunately, Quora does not have the option to copy the link for a comment - I can only do so for the answer.
* Although I say C++, I think it is also true for other languages like Java and C# (I am not 100% sure though).

like image 522
P.K. Avatar asked May 17 '18 17:05

P.K.


People also ask

Does the new operator call the constructor?

When new is used to allocate memory for a C++ class object, the object's constructor is called after the memory is allocated. Use the delete operator to deallocate the memory allocated by the new operator.

Is constructor automatically called by new operator in C++?

It is because the constructor is automatically called by the compiler and it is normally used to INITIALIZE VALUES.

Are constructors automatically called?

A constructor is a special initialization function that is automatically called whenever a class is declared. The constructor always has the same name as the class name, and no data types are defined for the argument list or the return type.

Which operator is used to call a constructor?

Constructor function They are named with capital letter first. They should be executed only with "new" operator.


Video Answer


1 Answers

If you search for constructor on the linked MSDN page, it says this:

When new is used to allocate memory for a C++ class object, the object's constructor is called after the memory is allocated.

In other words, a constructor is called if one exists. If none exists, none is called.

like image 152
Potatoswatter Avatar answered Nov 13 '22 15:11

Potatoswatter