We're working on an engine with a team and a specific feature would require us to access the memory addresses of each member by adding values to the class's address. This is demanded for a component save-load system, where each member of a component would be saved and then loaded back if the user loads the scene. Obviously, since users can also create components, we can't just go ahead and stick to manually setting each member's value -- because the ones created by users aren't known for us. While writing the post, I figured that virtual functions interrupted - originally I didn't have a clue why we couldn't reach the members.
In the following scenario, I want to access the componentID variable of the Component class.
Component.h:
class Component
{
private:
static int componentID_Count;
protected:
virtual void Start() {};
virtual void Tick() {};
friend class Entity;
public:
int componentID; // This is originally private, we set it to public in order to test the mentioned system
Component();
inline int GetID() { return componentID; }
};
And inside main():
Component c = Component();
std::cout << (&c + 1) << std::endl;
std::cout << "component address: " << &c << " offset size: " << offsetof(Component, componentID)
<< " component address + offset: " << (&c + offsetof(Component, componentID))
<< " component id address: " << &c.componentID << std::endl;
I saw offsetof() being recommended on many forums, my experience is the following:
- (&c + 1) returns an address 2 bytes after &c
- (&c + offsetof(Component, componentID)) returns an address 10 bytes after &c (and the offset size is said to be 8)
- &c.componentID is a byte after &c, as expected
Does anyone have a clue how to ignore/jump over virtuals and be able to manipulate the member values based on their addresses?