Let\'s say I have this Haskell code:
data RigidBody = RigidBody Vector3 Vector3 Float Shape -- position, velocity, mass an
The canonical way to do this in C++ is the inheritance-based solution given in Justin Wood's answer. Canonically, you endow the Shape with virtual functions that each kind of Shape
However, C++ also has union types. You can do "tagged unions" instead:
struct Ball { /* ... */ };
struct Square { /* ... */ };
struct Shape {
int tag;
union {
Ball b;
Square s;
/* ... */
}
};
You use the tag member to say whether the Shape is a Ball or a Square or whatever else. You can switch on the tag member and whatnot.
This has the disadvantage that a Shape is one int larger than the biggest of Ball and Square and the others; objects in OCaml and whatnot do not have this problem.
Which technique you use will depend on how you're using the Shapes.