In C it's fairly common to use void *
to create a generic collection. For example, if you wanted a generic linked list, you might write something like:
typedef struct node {
void *data;
struct node *next;
} node;
Then you could create one linked list of foo
, another linked list of bar
, and so on.
In C++, however, this is rarely useful. In a typical case, you'd want to write equivalent code as a template instead:
template <typename T>
class node {
T data;
node *next;
};
With older compilers, you could reduce the generated code by combining the two techniques. In this case, you'd use a collection of pointers to void to store the data, then have a template front-end that just handled casting T *
to void *
when you stored the data, and back from void *
to T *
when you retrieved the data.
Improvements in compilers/linkers have rendered this technique (almost?) entirely obsolete though. Older compilers would generate separate code for each type over which you instantiated your template, even where the instantiation type was irrelevant. Current compilers (or toolchains, anyway -- quite a bit of this is really handled by the linker) identify the identical code sequences, and merge them together automatically.
Bottom line: unless you need C compatibility, or you're writing a replacement operator new
/operator delete
, use of void *
in well written C++ is usually pretty rare.