Ch5.11: void*

Overview

A void* (pronounced “void pointer”) is a pointer that can hold the address of any object, regardless of its type. It is a typeless pointer. Because it has no type information, C++ restricts what you can do with it.

In this chapter, you will learn:

1. What is a void pointer?

A void* can store the address of any object. It is the most generic pointer type in C++.


int x{42};
double y{3.14};

void *p1 = ::std::addressof(x);   // ok
void *p2 = ::std::addressof(y);   // ok

But because void* has no type, C++ does not know:

2. You cannot dereference a void pointer

A void* does not point to a specific type, so C++ does not know what *p would mean.


void *p = ::std::addressof(x);

// *p;   // ❌ error: cannot dereference void*

To access the object, you must convert the pointer to a typed pointer. (Conversions will be introduced later.)

3. Pointer arithmetic is forbidden on void*

Pointer arithmetic requires knowing the size of the pointed‑to type. Since void has no size, arithmetic is not allowed.


void *p = ::std::addressof(x);

// p + 1;   // ❌ error: cannot do pointer arithmetic on void*

This restriction prevents accidental misuse.

4. void* and C‑style array decay

When a C‑style array decays, it becomes a pointer to its first element. That pointer can be stored in a void*.


int a[3]{1,2,3};

void *p = a;   // decay: a → &a[0], then stored in void*

But because void* is typeless:

It is simply a generic address.

5. void const* for read‑only memory

When pointing to memory that must not be modified, use:


void const *p = "Hello";   // pointer to read-only memory

This follows the rule from Ch2.8:

const applies to the left. Full stop.

void const* means “pointer to const void”, i.e., “pointer to read‑only memory of unknown type”.

6. Why void* exists

void* is used in low‑level programming where the type of the data is not known in advance. Examples include:

void* is a way to store “just an address” without type information.

7. void* does not bypass the type system

A void* does not magically allow you to treat memory as any type. It simply removes type information temporarily.

To use the memory, you must convert the pointer back to the correct type. (Conversions will be introduced later.)

8. Summary table

Operation Allowed? Reason
Store any object’s address ✔ yes void* is typeless
Dereference ❌ no No type information
Pointer arithmetic ❌ no void has no size
Decay from array ✔ yes array decays to &a[0]
Use for read‑only memory ✔ yes use void const*

Key takeaways