Why can converting a C++ Button* to its second base Clickable* change the address, and how does that break a void* callback?
answer
- each base subobject at its own offset
- conversions add the offset
- void* forgets the static type
- cast back to exactly what went in
basics
~20 sEach base is a subobject at its own offset inside Button, so a Clickable* may point past the Button's start. A void* round trip skips that adjustment: a pointer stored as Button* must come back as Button*, never straight as Clickable*.
solid answer
~40 sA `Button` derived from `Drawable` and `Clickable` contains both base **subobjects**, and two non-empty subobjects cannot share an address, so at least one base sits at a non-zero offset. Converting `Button*` to that base's pointer, implicitly or with `static_cast` or `dynamic_cast`, **adds the offset**; converting back subtracts it, and a null pointer stays null. Pointer comparison converts first, so `cp == bp` is true even when the raw addresses differ. Conversions that do not know both types skip the adjustment: `reinterpret_cast`, and a round trip through `void*`. A C callback that stores `&button` as `void*` and casts the `void*` to `Clickable*` has **undefined behaviour**; on one build it silently called `draw()` instead of `on_click()`. The rule is to convert to the exact type the receiver will cast back to before erasing it.
code
cpp · 31 lines#include <iostream>
struct Drawable {
virtual ~Drawable() = default;
virtual void draw() const = 0;
};
struct Clickable {
virtual ~Clickable() = default;
virtual void on_click() = 0;
};
struct Button : Drawable, Clickable {
void draw() const override {}
void on_click() override { std::cout << "clicked\n"; }
};
int main() {
Button ok;
Button* bp = &ok;
Drawable* dp = bp; // implicit upcast to the first base
Clickable* cp = bp; // implicit upcast to the second base: address adjusted
std::cout << static_cast<void*>(bp) << '\n'
<< static_cast<void*>(dp) << '\n'
<< static_cast<void*>(cp) << '\n';
std::cout << (cp == bp) << '\n'; // bp converted first: 1
std::cout << (static_cast<Button*>(cp) == bp) << '\n'; // downcast adjusts back: 1
Button* none = nullptr;
Clickable* still_none = none; // null stays null
std::cout << (still_none == nullptr) << '\n';
}go deeper
Remember that with two non-empty bases at least one base pointer differs numerically from the derived pointer, and that ordinary conversions handle it for you.
Explain subobject offsets, which casts adjust, why null stays null, and why pointer comparison still works across the conversion.
Diagnose the void* and reinterpret_cast failure modes, describe the undefined behaviour honestly, and name the sanitizer check that exposes it.
Treat every type-erasure boundary in a codebase with multiple bases as a review hotspot, and say what convention, such as converting before erasing, the team adopts.
## Why the addresses differ An object of a derived class contains a **base class subobject** for each of its bases, plus its own members. With one base, compilers commonly put the base at offset zero, so a `Derived*` and a `Base*` to the same object hold the same address. With two bases that is impossible for both: two non-empty subobjects cannot occupy the same bytes. So in ```cpp struct Button : Drawable, Clickable { /* ... */ }; ``` at least one of `Drawable` and `Clickable` lives at a non-zero offset inside `Button`. The standard does not fix the layout: it says the order in which base class subobjects are allocated in the most derived object is **unspecified**. Common ABIs place the bases in declaration order, so `Drawable` lands at offset 0 and `Clickable` after it; that is the implementation's choice, not a guarantee. On the build used for the code example, the `Clickable*` printed 8 bytes higher than the `Button*` and `Drawable*`, which held the same address. ## Conversions that adjust Every conversion that knows both the source and the target class applies the offset: | Conversion | Adjusts the address? | |---|---| | implicit `Button*` to `Clickable*` | yes | | `static_cast<Clickable*>(bp)` and back with `static_cast<Button*>(cp)` | yes | | `dynamic_cast` between them | yes | | `reinterpret_cast<Clickable*>(bp)` | **no** | | `Button*` to `void*`, then `void*` to `Clickable*` | **no** | Three details make the adjusting conversions safe: - A **null pointer stays null**. Converting a null `Button*` yields a null `Clickable*`, not the value 8; the compiler emits a null check for that. - **Comparison converts first.** `cp == bp` converts `bp` to `Clickable*` before comparing, so it is true even though `static_cast<void*>(cp)` and `static_cast<void*>(bp)` differ. - A virtual destructor lets `delete cp` destroy the whole `Button` and free the original address, because the destructor call knows the complete object. ## Where it goes wrong: erasing the type A `void*` remembers an address but not a type. The only cast from `void*` with defined meaning is back to the type that was originally stored (or to a type it can legitimately be accessed as). C-style callback APIs, thread-start routines, event queues and timer libraries pass "user data" exactly this way: ```cpp using Callback = void (*)(void* user_data); void on_event(void* user_data) { static_cast<Clickable*>(user_data)->on_click(); } fire(on_event, &ok); // &ok is a Button*: undefined behaviour ``` The `void*` holds the address of `Button`, which is the address of its `Drawable` part. Casting it to `Clickable*` performs no adjustment, so the call reads `Drawable`'s virtual table through a pointer it believes is a `Clickable`. That is **undefined behaviour**, and it rarely crashes politely. On the build tested, the call silently ran `draw()`, most likely because `draw()` occupies the virtual-table slot that `on_click()` occupies in `Clickable`'s table; another build may crash or do something else. Clang's `-fsanitize=vptr` check catches it at run time: `member call on address ... which does not point to an object of type 'Clickable'`. The fix is to convert before erasing: 1. Decide what type the receiver will cast the `void*` back to. 2. Convert to exactly that type first: `Clickable* target = &ok; fire(on_event, target);`. 3. In the callback, cast the `void*` back to that same type. The same reasoning rules out `reinterpret_cast` between related class pointers, storing pointers as integers and converting them back to a different base type, and `memcpy` of a `Button*` into a `Clickable*` variable. ## Identity checks across bases Comparing addresses after casting to `void*` does not tell you whether two base pointers refer to the same object, because they may sit at different offsets. Compare through a common type, or use `dynamic_cast<void*>`, which for a polymorphic type returns the address of the most derived object; that cast belongs with the RTTI material. ## What a senior answer adds - The layout is the implementation's choice, but the existence of an offset follows from distinct subobjects. - Virtual bases make the offset depend on the dynamic type, which is why a `static_cast` down from a virtual base is ill-formed. - Bugs come from type erasure, not from ordinary casts: audit every `void*` and `reinterpret_cast` boundary in code that uses several bases.
- Why does a C++ static_cast from Button* to Clickable* need a null check in the generated code?The standard requires a null pointer to convert to a null pointer of the target type. Adding the subobject offset blindly would turn null into a small non-null address, so the compiler emits a branch: if the source is null, produce null, otherwise add the offset. Conversion of a reference needs no such check, since a reference cannot be null in a valid program.
- How do you check in C++ whether a Drawable* and a Clickable* refer to the same object?Not by comparing them as `void*`, since the subobjects sit at different addresses. If you know the derived type, convert both to `Button*` and compare. If you do not, and the classes are polymorphic, compare `dynamic_cast<void*>(dp)` with `dynamic_cast<void*>(cp)`: each yields the address of the most derived object, so they are equal exactly when both point into the same object.
- A pointer to any base of an object always holds the object's address.
- reinterpret_cast is a faster static_cast between related class pointers.
- A void* can be cast to any base of the stored object's type.
- If cp == bp is true, their addresses as void* must be equal too.
- The standard fixes the first base at offset zero in the derived object.