The Analogy: An Unlabelled Parcel
Every pointer you have used so far is a labelled parcel. int* p says "there is an integer at this address"; the label tells the compiler how many bytes to read, how to interpret them, and what operations make sense. The label is doing real work.
A void* is the same parcel with the label torn off. The address is still perfectly good — you simply no longer know what is inside. You cannot open it (*p will not compile), you cannot count parcels along the shelf (p + 1 is meaningless without a size), and you certainly cannot ask it how big it is. All you can do is carry it around, compare it, and hand it to somebody who knows what it should be.
That last part is the entire use case. A void* lets you write a function that transports data without caring about its type — which is how C achieved generic code, and why every C callback API in existence takes one. The price is that the knowledge of the real type has moved out of the compiler's hands and into your head, or into a separate tag you have to carry alongside. Get it wrong and the compiler cannot help you: casting a void* back to the wrong type is undefined behaviour that compiles silently.
In C++ you should reach for templates, std::variant or virtual functions instead. void* remains worth understanding because you will meet it at every C boundary, in malloc, in memcpy, in qsort, and in every thread and callback API written before templates existed.
Syntax or Core Structure
#include <iostream>
#include <string>
int main() {
int count = 42;
double ratio = 3.5;
std::string name = "Ada";
// Any object pointer converts to void* implicitly -- no cast needed
void* p = &count;
p = ∶
p = &name;
// Going back the other way REQUIRES an explicit cast
p = &count;
// std::cout << *p; // ERROR: cannot dereference void*
// std::cout << p[0]; // ERROR: no size, no indexing
// ++p; // ERROR: no arithmetic
int* backToInt = static_cast<int*>(p); // you assert the type here
std::cout << *backToInt << "\n"; // 42
// Printing the address itself is one of the few direct uses
std::cout << "address: " << p << "\n";
// Comparison works
void* q = &count;
std::cout << "same object? " << (p == q ? "yes" : "no") << "\n";
// The classic trap: nothing checks that the cast is right
p = ∶
int* wrong = static_cast<int*>(p); // compiles fine
std::cout << "garbage: " << *wrong << "\n"; // UNDEFINED BEHAVIOUR
// nullptr is a valid void*
void* nothing = nullptr;
if (nothing == nullptr) {
std::cout << "points nowhere\n";
}
}
Note the asymmetry, which is the safety model in one line: *converting to void* is implicit and always safe; converting from it needs an explicit cast and is entirely your responsibility.*
Technical Depth: What You Lose, and What You Get Back
The three things a void* cannot do
| Operation | int* | void* |
|---|---|---|
Dereference *p | Yes | No — the size is unknown |
Index p[i] | Yes | No — indexing needs a stride |
Arithmetic p + 1 | Yes | No — no stride to scale by |
| Assign from any object pointer | No | Yes, implicitly |
Compare ==, != | Yes | Yes |
Hold nullptr | Yes | Yes |
| Print as an address | Needs a cast | Directly |
GCC permits void* arithmetic as an extension, treating the stride as 1. Do not rely on it; it is not standard C++. Cast to unsigned char* when you want byte stepping.
Casting back: which cast, and why not reinterpret_cast
int value = 7;
void* p = &value;
int* a = static_cast<int*>(p); // correct for void* -> T*
int* b = (int*)p; // C style: works, says nothing
int* c = reinterpret_cast<int*>(p); // legal but overkill and misleading
Use static_cast. Round-tripping T* to void* and back with static_cast is explicitly guaranteed to give you the original pointer. reinterpret_cast is for genuinely unrelated types and signals a much stronger claim than you are actually making; reserve it for that.
One thing static_cast will not do is drop const:
const int fixed = 3;
const void* cp = &fixed;
const int* back = static_cast<const int*>(cp); // fine
// int* bad = static_cast<int*>(cp); // ERROR -- good
const void* is the right parameter type for a function that only reads, and it is what std::memcmp takes.
Byte-level work: cast to unsigned char*
Since void* has no arithmetic, byte manipulation goes through unsigned char*, whose stride is 1 by definition:
void copyBytes(void* dest, const void* source, std::size_t count) {
unsigned char* d = static_cast<unsigned char*>(dest);
const unsigned char* s = static_cast<const unsigned char*>(source);
for (std::size_t i = 0; i < count; ++i) {
d[i] = s[i];
}
}
That is std::memcpy's signature and roughly its body, and it explains why the standard library's memory functions all take void*: they genuinely do not care what the bytes mean.
The C generic-function pattern
Before templates, this was how you wrote code that worked for any type:
#include <cstdlib>
int compareInts(const void* a, const void* b) {
int left = *static_cast<const int*>(a);
int right = *static_cast<const int*>(b);
return (left > right) - (left < right);
}
int main() {
int values[5] = {5, 2, 9, 1, 7};
std::qsort(values, 5, sizeof(int), compareInts); // sorted
}
qsort takes a void* array, a count, the element size (because it cannot work it out) and a comparator that unpacks the void*s itself. Compare it with the C++ version:
std::sort(values, values + 5); // that is the whole thing
qsort (void*) | std::sort (template) | |
|---|---|---|
| Type checked | No | Fully |
| Element size | You pass it | Known |
| Comparator | Indirect function call per comparison | Inlined |
| Speed | Slower | Typically much faster |
| Wrong type | Compiles, then corrupts | Will not compile |
std::sort is faster because it keeps the type: the comparison inlines instead of jumping through a function pointer.
The callback user_data idiom
Every C API that lets you register a callback gives you one void* to smuggle your own context through. This is the pattern you will genuinely have to write:
struct Counter { int calls = 0; std::string label; };
// A C-compatible callback: fixed signature, context arrives as void*
void onEvent(int code, void* userData) {
Counter* c = static_cast<Counter*>(userData); // cast back to what we passed
++c->calls;
std::cout << c->label << " got code " << code << "\n";
}
void registerHandler(void (*fn)(int, void*), void* userData); // C-style API
int main() {
Counter c{0, "sensor"};
registerHandler(onEvent, &c); // hand our address across
}
The rule that makes this safe: the code that casts back must be the same code that cast in. If onEvent and the &c at the call site are not maintained together, nothing will warn you when they drift apart.
Why a void* cannot be safely queried
There is no way to ask a void* what it points at. No typeof, no size, no dynamic_cast (that needs a polymorphic class type). If you must carry the type, carry it explicitly:
enum class Kind { Int, Double, Text };
struct Tagged {
Kind kind;
void* data;
};
void print(const Tagged& t) {
switch (t.kind) {
case Kind::Int: std::cout << *static_cast<int*>(t.data); break;
case Kind::Double: std::cout << *static_cast<double*>(t.data); break;
case Kind::Text: std::cout << *static_cast<std::string*>(t.data); break;
}
}
That works, and it is exactly the hand-rolled version of std::variant — which does the same thing with the tag maintained by the compiler and the casts checked:
#include <variant>
std::variant<int, double, std::string> value = 3.5;
if (std::holds_alternative<double>(value)) {
std::cout << std::get<double>(value); // throws if you guess wrong
}
Function pointers are not object pointers
void* is for pointers to objects. Converting a function pointer to void* is not portable standard C++ (POSIX requires it to work for dlsym, which is why the practice persists). Use a correctly typed function pointer, or std::function.
What to use instead
void* was for | Modern C++ |
|---|---|
| Any-type container or algorithm | Templates |
| One of a known set of types | std::variant |
| Any type at all, type-safely | std::any |
| A callback plus context | std::function and a lambda capture |
| Runtime polymorphism | A base class with virtual functions |
| Raw byte buffers | std::byte*, std::span<std::byte> |
Every one of those keeps the type information the void* throws away, and every one turns a runtime disaster into a compile-time error.
Real World Example: Wrapping a C-Style Event Callback
This is the situation that will actually put a void* in your code: a C library — a GUI toolkit, a network stack, a device driver — takes a function pointer with a fixed signature plus one void* of your own. You cannot change its signature, so the job is to get your typed C++ object safely across that gap and confine the unsafety to as few lines as possible.
#include <cstddef>
#include <iostream>
#include <string>
#include <vector>
// ---------------------------------------------------------------
// This block is the C library. You do not get to change it.
// ---------------------------------------------------------------
using EventHandler = void (*)(int code, const char* message, void* userData);
struct Subscription {
EventHandler handler = nullptr;
void* userData = nullptr;
};
class EventBus {
public:
void subscribe(EventHandler handler, void* userData) {
subscribers.push_back(Subscription{handler, userData});
}
void publish(int code, const char* message) {
for (const Subscription& s : subscribers) {
s.handler(code, message, s.userData); // context comes back out
}
}
private:
std::vector<Subscription> subscribers;
};
// ---------------------------------------------------------------
// This is our code. Typed, testable, and free of void*.
// ---------------------------------------------------------------
class Logger {
public:
explicit Logger(std::string name) : label(std::move(name)) {}
void record(int code, const std::string& message) {
++handled;
if (code >= 500) ++errors;
std::cout << "[" << label << "] " << code << " " << message << "\n";
}
std::size_t handledCount() const { return handled; }
std::size_t errorCount() const { return errors; }
const std::string& name() const { return label; }
private:
std::string label;
std::size_t handled = 0;
std::size_t errors = 0;
};
class Counter {
public:
void bump(int code) {
++total;
if (code >= 500) ++failures;
}
std::size_t totalSeen() const { return total; }
std::size_t failuresSeen() const { return failures; }
private:
std::size_t total = 0;
std::size_t failures = 0;
};
// The ONLY two functions in the program that touch void*.
// Each is a two-line shim: cast back, then call a typed method.
void loggerTrampoline(int code, const char* message, void* userData) {
Logger* logger = static_cast<Logger*>(userData);
logger->record(code, message ? message : "");
}
void counterTrampoline(int code, const char* /*message*/, void* userData) {
static_cast<Counter*>(userData)->bump(code);
}
int main() {
EventBus bus;
Logger appLog("app");
Logger auditLog("audit");
Counter stats;
// Each subscribe pairs a trampoline with the object it will cast to.
bus.subscribe(loggerTrampoline, &appLog);
bus.subscribe(loggerTrampoline, &auditLog);
bus.subscribe(counterTrampoline, &stats);
bus.publish(200, "request ok");
bus.publish(404, "not found");
bus.publish(500, "database unreachable");
bus.publish(503, "upstream timeout");
std::cout << "\n-- totals --\n";
for (const Logger* log : {&appLog, &auditLog}) {
std::cout << log->name() << ": " << log->handledCount()
<< " events, " << log->errorCount() << " errors\n";
}
std::cout << "counter: " << stats.totalSeen() << " events, "
<< stats.failuresSeen() << " failures\n";
}
Output:
[app] 200 request ok
[audit] 200 request ok
[app] 404 not found
[audit] 404 not found
[app] 500 database unreachable
[audit] 500 database unreachable
[app] 503 upstream timeout
[audit] 503 upstream timeout
-- totals --
app: 4 events, 2 errors
audit: 4 events, 2 errors
counter: 4 events, 2 failures
The structural point is where the void* lives. Logger and Counter know nothing about it — they have ordinary typed methods, they can be unit-tested with no event bus in sight, and neither contains a cast. All the danger is concentrated in two three-line trampoline functions whose entire job is to restore the type the C API discarded. When something goes wrong with a void*, that is where you look, and there is nowhere else it could be.
Notice that the same loggerTrampoline serves both appLog and auditLog. The function is stateless; the state arrives through userData on every call. That is exactly what the void* buys — one C-compatible function pointer can front any number of distinct objects, which a plain function with captured state could not do. And note that counterTrampoline casts to a completely different class through the same void* slot; the bus stores both in one std::vector<Subscription> without knowing either type.
The invariant that makes it safe is the pairing: bus.subscribe(loggerTrampoline, &appLog) says "when you call this function, hand it that address." The cast inside is correct only because of what the call site passed. Nothing checks it — pass &stats with loggerTrampoline and the code compiles cleanly, then calls Logger::record on a Counter, and the behaviour after that is undefined. Keeping each trampoline immediately adjacent to nothing but its one cast, and naming both after the type they expect, is the discipline that keeps the pairing visible.
Two smaller details are load-bearing. message ? message : "" guards against the C API passing a null const char*, which a C library is entitled to do and which would otherwise construct a std::string from nullptr — undefined behaviour. And the objects (appLog, auditLog, stats) must outlive the subscription: the bus holds bare addresses with no ownership, so if these were locals in a function that returned while the bus lived on, every stored void* would dangle. A void* conveys no lifetime information whatsoever, which is a second thing the type system would ordinarily have helped with.
In pure C++ the whole arrangement collapses to one line, because a lambda can capture the context the void* was smuggling:
std::vector<std::function<void(int, const std::string&)>> subscribers;
subscribers.push_back([&appLog](int code, const std::string& msg) {
appLog.record(code, msg);
});
No casts, no trampolines, no possible type mismatch. Use that whenever the API is yours. Use the trampoline pattern when it is not.
Common Mistakes
- Dereferencing a
void*.*pdoes not compile, and it should not — there is no size to read. - Doing arithmetic on it.
p + 1has no defined stride. Cast tounsigned char*first. - Casting back to the wrong type. It compiles silently and the result is undefined behaviour. This is the bug
void*exists to enable. - Using
reinterpret_castfor the round trip.static_castis correct and guaranteed;reinterpret_castoverstates the claim. - Casting away
const. If it arrived asconst void*, it must go back toconst T*. - Passing the address of a temporary or a local that dies first. The callback fires later and the
void*dangles. - Assuming you can inspect it. There is no way to ask a
void*what it points at. Carry a tag, or usestd::variant. - Converting function pointers through
void*. Not portable standard C++. - Using
void*for genericity in new C++ code. Templates do the same job with full type checking and better speed. - Forgetting the element size at a C boundary.
qsortandmemcpyneed a count in bytes or elements because thevoid*cannot supply it.
Best Practices
- Prefer templates,
std::variant,std::anyor virtual functions. Reach forvoid*only at a C boundary you do not control. - Confine every cast to a thin trampoline function so all the unsafety sits in one reviewable place.
- Always
static_cast, never a C-style cast, when converting back. - Use
const void*for read-only parameters. - Cast to
unsigned char*(orstd::byte*) for byte work, never rely onvoid*arithmetic extensions. - Keep the pointer and its length together. A
void*on its own is half the information. - Guarantee the pointee outlives the callback.
void*carries no ownership and no lifetime. - Name the trampoline after the type it casts to, so a mismatched registration is visible at the call site.
- Null-check anything a C API hands you before dereferencing it.
Practice Exercises
- Store the addresses of an
int, adoubleand astd::stringin the samevoid*variable in turn, casting each back and printing it. Then deliberately cast thedouble's address toint*, print the result, and explain why the compiler said nothing. - Write
void swapBytes(void* a, void* b, std::size_t size)that exchangessizebytes between two addresses by casting tounsigned char*. Test it on twoints and on twodoubles with the same function. - Write a
Taggedstruct holding aKindenum and avoid*, plus adescribefunction that switches on the tag and casts accordingly. Then rewrite it withstd::variantand list the specific mistakes the variant version makes impossible. - Take the trampoline example and add a third subscriber class of your own. Then, in a comment, describe exactly what would happen if you registered it with
loggerTrampolineby mistake, and what compiler diagnostic you would get.