Void Pointers in C++
For understanding the concept of void pointers, we should note that we cannot assign the address of one data-type variable to a pointer of another data-type variable. Consider the following:
Note that we can not assign the address of float
type variable to a pointer to int
as:
float y; int *p; p = &y; //illegal statement
Similarly, see the following:
float *p; int x; p = &x; //illegal statement
That means, if variable-type and pointer-to-type is same then only we can assign the address of that variable to pointer variable. If both, i.e., the data-type of the variable and the data-type pointed to by the pointer variable, are different then we can not assign the address of variable to pointer variable. But this impossible thing is made possible in C++ by declaring pointer variables as void
as follows:
void *p;
The above pointer is called pointer to void
type. That means pointer p
can point to any type of data like int
,float
, etc. For example:
void *p; int x; float y; p = &x; //legal statement p = &y; //legal statement
The above statement are perfectly fine in C++ and they depict the use of void pointers.