The void pointer is a pointer to a value whose type and size are unknown. I will give an example of how it can be used in C - although other commentators are correct, saying that by and large it should not be used (and, in fact, not needed) in C ++.
Suppose you have a structure in which a key and a value are stored. It can be defined as follows:
typedef struct item_t { char *key; int value; } item_t;
Thus, you can use this structure to match any string key with an integer value. But what if you want to keep some arbitrary value? Maybe you want some keys to correspond to integers, and some keys to correspond to doubles? You must define your structure so that it tracks (using a pointer) a value of an arbitrary type and size. void * is suitable for the account in this case:
typedef struct item_t { char *key; void *value; } item_t;
Now, if your value is int, you can get its value with (int *) value , or if its value is double, you can do it with (double *) value . This assumes, of course, that the code using the structure knows what type it expects to see in which context.
However, in C ++ the same functionality is usually achieved not with void * , but with the use of things like templates or a superclass from which all your types go off (for example, Object in Java), the list of objects can store some lines, some Integer and etc.).
source share