The void*
generic pointer type can be type-casted to any other data type pointer. However, being a generic pointer type, the void*
pointer cannot be de-referenced. Type-casting must be done to access the value the pointer it is pointing to.
Implicit conversion from a void*
pointer to another pointer type is possible in C, but C++ does not follow the same rule. In C++, explicit conversion is needed to convert a void*
pointer to another pointer type.
Note: To know about the differences between implicit type-casting and explicit type-casting, visit here.
There are differences in how a void*
generic pointer is treated in the two languages. The following code snippets will help us understand these differences better.
Let's try to convert a generic pointer type to another type in C:
#include<stdio.h>int main() {//generic pointer typevoid* ptr;//implicit conversion to int* from void*int* numPtr = ptr;int x = 10;//int pointer pointing towards variable xnumPtr = &x;printf("%d",*numPtr);}
Line 6: Implicit conversion of ptr
from void*
to int*
is allowed in C.
Line 9: After the conversion, we also assign an int
variable's address to the numPtr
to show that after the conversion.
Line 10: We can still access the int
element the numPtr
is pointing towards.
The above example would not be valid if we tried to use implicit conversion in C++:
#include <iostream>using namespace std;int main() {void* ptr;//implicit conversion to int* from void*int* numPtr = ptr;}
Line 7: It can be seen in the error that C++ restricts the direct conversion of a void*
pointer to an int*
pointer, and we need another way to handle these conversions.
We can handle the generic pointer conversion in C++ by writing the code and conversions explicitly:
#include <iostream>using namespace std;int main() {void* ptr;//explicit conversion to int* from void*int* numPtr = (int*) ptr;int x = 10;//int pointer pointing towards variable xnumPtr = &x;cout<<*numPtr;}
Line 7: Explicitly addressing the generic pointer ptr
conversion to int
type solves the issues we faced in the previous code example.
The generic void*
pointer concept is the same in both languages. However, the main difference is visible in the way type-casting is implemented. C uses implicit conversions, while C++ uses explicit conversions.
Free Resources