top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Why should I use new instead of trustworthy old malloc()?

+2 votes
100 views
Why should I use new instead of trustworthy old malloc()?
posted Dec 23, 2014 by Alwaz

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+2 votes
 
Best answer

Constructors/destructors, type safety, overridability.

Constructors/destructors: unlike malloc(sizeof(Fred)), new Fred() calls Fred's constructor. Similarly, delete p calls *p's destructor.

Type safety: malloc() returns a void* which isn't type safe. new Fred() returns a pointer of the right type (a Fred*).

Overridability: new is an operator that can be overridden by a class, while malloc() is not overridable on a per-class basis.

answer Dec 24, 2014 by Mohammed Hussain
Similar Questions
+4 votes

what is difference between new and malloc ??

0 votes

I consider myself a python programmer, although C++ was one of the first languages I learned (not really deeply and long time ago).

Now I decided to retake C++, to broaden my view of the business. However, as I progress in learning C++, I cannot take out of my head one question

Why to use C++ instead of python?

It is not ranting against C++. I was/am looking for small-medium projects to exercise my C++ skills. But I'm interested in a "genuine" C++ project: some task where C++ is really THE language (and where python is actually a bad as initial choice).

The usual argument in favor of C++ (when comparing to python) is performance. But I'm convinced that, in general, the right approach is "python-profiling-(extension/numpy/Cython/...)". At least for a python
programmer. I might be wrong, though.

This is, perhaps, a bit off-topic, but I really want to know the thoughts of experienced python programmers on it.

+4 votes

I believe option 1 is more correct, dont know why?

1) int *p = malloc(sizeof(int)*l);
2) int *p = (int *)malloc(sizeof(int)*l);
...