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:
Allocates memory for the object.
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.)
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).
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.
It is because the constructor is automatically called by the compiler and it is normally used to INITIALIZE VALUES.
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.
Constructor function They are named with capital letter first. They should be executed only with "new" operator.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With