Behaviour of new and malloc in C and C++

c, c++, pointers

Solution

You are confusing `operator new` with the `new` operator. `operator new` just allocates raw memory and returns a `void*`, whereas `new T` also calls the constructor after allocation and returns a `T*`.

Also, you have to cast the result of `malloc` in C++, because unlike C, C++ does not allow implicit conversions from `void*` to other pointer types. Note that `void*` is used very rarely in C++.

Problem

In C, it is considered poor form to typecast the result of a call to `malloc`. However, it seems that the result of calls to `malloc` in C++ should be typecast, even though both `malloc` and `new` have return type `void*` and calls to `new` are not typecast. Is there a reason why in C++ the void pointer returned by `new` is automatically promoted while the void pointer returned by `malloc` isn't?

Original source

Related problems