Search code examples
c++vtable

Offset to complete object from subobject


I need to get the front-most address of a complete object even if what I have happens to be a subobject.

The current version of my experimental smart pointer can only compare locations of a complete object and one of it's subobjects. It is simply storing their addresses and their sizes in bytes and see if they overlap. The problem lies in comparing two subobjects of a complete object in the case of multiple inheritance. Since these subobjects will not overlap each other they wont be recognized as belonging to the same object. This would require the offset to the "head" of the complete object from the subobject to gain the address of the complete object for comparison.

Note that this comparison has nothing to do with accessing or destructing the objects. It's only to map handles to an object, no matter what the sub type of the handle is. The handle itself is responsible for holding the type and disposing of it once no more references to the same object exist.

Is it possible to hijack the vtable in order to get the offset to the complete object? I've been unable to find a standard function that allows you to do this. My assumption is that abusing the vtable is highly implementation dependent and will most likely not be reusable on another compiler. Using typeid on an object manages to work out what the complete object is given a subobject, so I believe it's possible to achieve. Too bad it wont return that address...

Just to be clear: I do not need the offset of the subobject inside another object. I need to do it the other way around and find the complete object from the subobject without knowing the complete object's type.


Solution

  • dynamic_cast<void*>(myBaseObject);
    

    Doing this will get you a pointer to the most derrived type, i.e. the most complete object. You can do what you like with that once you've got that pointer.