Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

void pointers: difference between C and C++

I'm trying to understand the differences between C and C++ with regards to void pointers. the following compiles in C but not C++ (all compilations done with gcc/g++ -ansi -pedantic -Wall):

int* p = malloc(sizeof(int));

Because malloc returns void*, which C++ doesn't allow to assign to int* while C does allow that.

However, here:

void foo(void* vptr)
{
}

int main()
{
    int* p = (int*) malloc(sizeof(int));
    foo(p);
    return 0;
}

Both C++ and C compile it with no complains. Why?

K&R2 say:

Any pointer to an object may be converted to type void * without loss of information. If the result is converted back to the original pointer type, the original pointer is recovered.

And this pretty sums all there is about void* conversions in C. What does C++ standard dictate?

like image 474
zaharpopov Avatar asked Nov 15 '09 06:11

zaharpopov


2 Answers

In C, pointer conversions to and from void* were always implicit.

In C++, conversions from T* to void* are implicit, but void* to anything else requires a cast.

like image 111
GManNickG Avatar answered Oct 20 '22 14:10

GManNickG


C++ is more strongly-typed than C. Many conversions, specially those that imply a different interpretation of the value, require an explicit conversion. The new operator in C++ is a type-safe way to allocate memory on heap, without an explicit cast.

like image 36
Vijay Mathew Avatar answered Oct 20 '22 15:10

Vijay Mathew