You did, except that it’s not one pointer, it’s two. This is one way that rust is different than C++; the vtable isn’t stored with the data, but separately, with the “trait object” itself being two pointers to the two things.
Which “data” is the vtable stored with in C++? An object contains only a pointer to its vtable, not the vtable itself...
struct ClassVTable {
void (*firstMethod)();
void (*secondMethod)();
}
struct Class {
struct ClassVTable *virt;
int firstMember;
int secondMember;
};
and a pointer to it looks like: struct Class *objectRef;
A language that uses fat pointers, like rust, has this separated completely: struct Class {
int firstMember;
int secondMember;
};
struct FatPointerToClass {
struct ClassVTable *virt;
struct Class *data;
}
FatPointerToClass objectRef; // note lack of pointer, it'd be stored on the stack directly for eg.
This means a much simpler object layout in exchange for passing around larger pointers, and it's a good fit for trait-based typing since it doesn't require you to know all possible interface subtypes of the object in order to describe or use its layout.(please note that I'm using C struct to be precise about the concept, and this should not be taken as a perfectly verbatim description of the actual object layouts in memory)
In other words, in Rust, a pointer to a shape is
(pointer to vtable, pointer to data)
whereas, in C++, a pointer to a shape is (pointer to shape)
where shape is (pointer to vtable, data)
If that's incorrect, I'm quite happy to be corrected! This isn't an area I'm an expert in.I get it now, that you meant the “pointer to the vtable” under “vtable” in your original post.