Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't new require a cast to the pointer even though malloc requires it?

The definition of new in the <new> header is:

 void* operator new(size_t);

And the definition of malloc is as stated:

 void* malloc(size_t);

Now, as C++ is a strongly typed language, it requires a cast from the programmer to convert a void* pointer to the type the programmer requires... In malloc, we have to perform a cast, but not in new, though both return a void* pointer. Why?

like image 672
bhuwansahni Avatar asked Mar 07 '12 06:03

bhuwansahni


People also ask

Does malloc need a cast?

In C, you don't need to cast the return value of malloc . The pointer to void returned by malloc is automagically converted to the correct type. However, if you want your code to compile with a C++ compiler, a cast is needed.

Why is typecasting required with malloc?

malloc return a generic type pointer. Because generic pointer is of type void (void *p,p is generic pointer). Void pointer can hold any type of data so it is needed to typecast it.

Do you have to cast malloc in C++?

Declaration for malloc: void *malloc(size_t *size*); In C it is not mandatory to cast a void pointer to any other pointers, but in C++ is must. p = malloc(sizeof(int) * n);

What is a void pointer in C?

The void pointer in C is a pointer that is not associated with any data types. It points to some data location in the storage. This means it points to the address of variables. It is also called the general purpose pointer. In C, malloc() and calloc() functions return void * or generic pointers.


1 Answers

Because when you're using new, you (normally) use a "new expression", which allocates and initializes an object. You're then assigning the address of that object to a pointer to an object of the same (or parent) type, which doesn't require a cast. A normal new expression (i.e., not a placement new) will invoke operator new internally but the result of the new expression is not just the result from operator new.

If you invoke operator new directly, then you need to cast its result to assign the return value to a non-void pointer, just like you have to do with the return from malloc.

like image 112
Jerry Coffin Avatar answered Nov 15 '22 14:11

Jerry Coffin