Programming C++   «Prev  Next»
Lesson 6 The generic pointer type
Objective Examine the generic pointer type void*.

C++ Generic Pointer Type

The keyword void is used as the return type of a function not returning a value and to indicate an empty argument list to a function. More important in C++, however, is the use of void* as a generic pointer type.
A generic pointer can be assigned a pointer value of any type, but it may not be dereferenced. It would not make sense to dereference a pointer to a void value.
Pointer casts
Unlike ANSI C, a generic pointer is not assignment-compatible with an arbitrary pointer type. This means C++ requires that generic pointers be cast to an explicit type for assignment to a nongeneric pointer value.

Here are some examples of legal and illegal expressions stemming from the use of void*:
void*  gp;    //generic pointer
int*  ip;     //int pointer
char*  cp;    //char pointer

gp = ip;      //legal conversion
ip = static_cast<int*>(gp); //explicit cast required
                            //in C++ but not in C
cp = ip;      //illegal conversion
*ip = 15;     //legal dereference of pointer to int
*ip = *gp;    //illegal generic pointer dereference