0
What is the use of void pointer in c++?
2 Respuestas
+ 1
Usually when declaring a pointer, the compiler needs to know which kind of type of the variable that the pointer points to so that it can get the right value of the variable through the reference operation.
void pointer is when you don't know in advance the kind of type of the variable it would point to. But when you want to get the right value you have to cast to the right type.
+ 1
Here's an example for you:
#include <iostream>
using namespace std;
int main() {
void* p;
int a = 12;
char c = '#';
double d = 3.14;
p = &a;
cout << *(int*)p << endl;
p = &c;
cout << *(char*)p << endl;
p = &d;
cout << *(double*)p << endl;
return 0;
}
If you don't cast void* to the right type, you'll get wrong values. Try to cast it to different types when printing to see the results.