Hi, I'm creating a component based entity model for my game(not to confuse with an ECS). Because I decided that I won't need dynamic addition and removal of components, I got the idea to implement components with multiple inheritance: I have an Entity Base class which only has a few functions for entity lifetime etc. Every component virtually inherits from that class. At the end an entity inherits from all the components it needs. Now from time to time a component has to access another component like this:
dynamic_cast<OtherComponent*>(this)->doOtherComponentsStuff()
The Movement component for example has to access the velocity component every frame. This results in a lot of dynamic_casts and poor performance. But because the components of an entity never change I would call dynamic_cast only once(in the ctor), save the offset of the resulting address and use it later to access the other component without the performance penalty of dynamic_cast. Here's what I mean:
class Entity
{
public:
virtual ~Entity() = default;
};
class Derived2 : public virtual Entity
{
public:
void doThat()
{
std::cout << "Did that\n";
}
};
class Derived1 : public virtual Entity
{
public:
Derived1()
{
m_derived2Off = reinterpret_cast<intptr_t>(dynamic_cast<Derived2*>(static_cast<Entity*>(this))) - reinterpret_cast<intptr_t>(this);
}
void doIt()
{
getDerived2()->doThat();
}
private:
intptr_t m_derived2Off;
Derived2 *getDerived2()const
{
return reinterpret_cast<Derived2*>(m_derived2Off + reinterpret_cast<intptr_t>(this));
}
};
class Player final:
public Derived1,
public Derived2
{
};
int main()
{
Player obj;
obj.doIt();
}
It worked for me, but I'm not sure if there might be some undefined behavior involved.