[Solved] differences between new and malloc in c++ [duplicate]


malloc allocates memory only, it doesn’t invoke constructors which can leave objects in an indeterminate state.

In C++ you should almost never use malloc, calloc or free. And if possible avoid new and new[] as well, use object instances or vectors of instances instead.


As for your second question (which is really unrelated to the first), *(myBoxArray2).printer(23) is wrong since the the . selection operator have higher precedence than the dereference operator *. That means first of all that you use the . member selector on a pointer which is invalid, and that you attempt to dereference what printer returns which is also wrong since it doesn’t return anything.

You want (*myBoxArray2).printer(23) (note the location of the asterisk is inside the parentheses), which is exactly the same as myBoxArray2->printer(23).

Also note that myBoxArray2->printer(23) is the same as myBoxArray2[0].printer(23).

solved differences between new and malloc in c++ [duplicate]