Changing the type pointed to

The static_cast operator is used to convert with a compile time check, but not a runtime check, so this means that the pointers must be related. The void* pointer can be converted to any pointer, so the following compiles and makes sense:

    int *pi = static_cast<int*>(malloc(sizeof(int)));     *pi = 42;     cout << *pi << endl;     free(pi);

The C malloc function returns a void* pointer so you have to convert it to be able to use the memory. (Of course, the C++ new operator removes the need for such casting.) The built-in types are not "related" enough for static_cast to convert between pointer types, so you cannot use static_cast to convert an int* pointer to a char* pointer, even though int and char are both integer ...

Get Beginning C++ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.