You are here:

C++/why new operator in cpp

Advertisement


Question
QUESTION: 1>c supports stack memory allocation for objects by simple invoking costructor with out using "new".but what is need to to introduce 'new' operator in cpp(although malloc and calloc were doing the job in 'c')?
2>what is difference between new int[5] and new int(5),and how 'delete' or 'delete[]' work in each case?
3>is the above statement execute any wrapper/primitive type of constructor?if yes how if know how it allocates memory?

thanks in advance..

ANSWER: See http://www.yolinux.com/TUTORIALS/Cpp-DynamicMemory.html


---------- FOLLOW-UP ----------

QUESTION: sir 2> and 3> are not clear .whether new only operates on constructor?if yes then how it allocates memory for primary type?plz elaborate..
thank you for quick response.

Answer
Where T is some type,

new T ; allocates memory by calling operator new()
http://www.cplusplus.com/reference/new/operator%20new/

If T has a non-trivial default constructor, it is then invoked to initialize the object.
If T is a type with no constructor (say int), this step is skipped.
http://eli.thegreenplace.net/2011/02/17/the-many-faces-of-operator-new-in-c/  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.