I'm trying to design class hierarchy for my physical simulations. I really want to share variables (e.g. Vec3d pos
, Quat4d rot
) between classes which depend on each other by more complex graph of multiple-inheritance. I extracted simple example what is the problem (full code is here):
// ==== prefabricates for classes ... I was thinking this will solve the problem
class _pos { public: Vec3d pos;};
class _rot { public: Quat4d rot;};
// === classes
class KinematicBody : public _pos, public _rot{
// pos, rot ... inherited
void toGLmat( float * mat ); // make Opengl 4x4 matrix for rendering
};
class PointBody : public _pos, public Updateable {
public:
// pos ... inherited
Vec3d vel,force;
double mass;
inline void update_(double dt){ vel.add_mul(force, dt); pos.add_mul(vel,(dt/mass)); }; // can be called as obj->PointBody::update_(dt);
virtual void update (double t, double dt ){ update_(dt); }; // implements Updateable
};
// !!!! HERE IS THE PROBLEM
class RigidBody : public PointBody, public KinematicBody { // WARRNING : both PointBody and KinematicBody inheriate "pos"
public:
// pos,vel,force,mass,rot ... inherited
Mat3d momentOfInertia;
Vec3d torque;
Vec3d angular_velocity;
};
I tried to run following test to make sure that KinematicBody::pos
, PointBody::pos
, RigidBody::pos
all share the same piece of memory (full code here):
RigidBody rb;
KinematicBody * kb = &rb;
PointBody * pb = &rb;
rb. pos.set(1.0); printf( "%f %f %f\n", rb.pos.x, kb->pos.x, pb->pos.x );
kb->pos.set(2.0); printf( "%f %f %f\n", rb.pos.x, kb->pos.x, pb->pos.x );
pb->pos.set(3.0); printf( "%f %f %f\n", rb.pos.x, kb->pos.x, pb->pos.x );
I expected result like
1.0000 1.0000 1.0000
2.0000 2.0000 2.0000
3.0000 3.0000 3.0000
But instead I got following error:
error: request for member ‘pos’ is ambiguous
rb. pos.set(1.0); printf( "%f %f %f\n", rb.pos.x, kb->pos.x, pb->pos.x );
This error can be probably resolved by making
class RigidBody : public PointBody, public _rot {
instead of
class RigidBody : public PointBody, public KinematicBody {
but than I cannot inherit void toGLmat( float * mat );
from KinematicBody
... and in general it makes composition of classes very unconveneient
Is there any way how to achieve this sharing? I was thinking that by making prefabricates like _pos
and _rot
I can achieve this, but apparently not.