Reputation: 392
I am implementing some classes for shapes. Is there a way of avoiding code repetition and wasting memory at the same time?
Basically, I would like to have a variable in the base class that is a constant and only has one copy per derived class (like a static member), but with a different value for each derived class.
For example, I want to define functions that work on the inertia tensor for the derived classes; for each shape, the inertia tensor is a constant, so I don't want to have a copy of the same constant for every instance.
However, instead of declaring the same variable and defining the same function for every derived class, I'd like to declare a single variable at the base class and have a generic function in the base class as well, say to change the inertia tensor from world to local coordinates and vice versa.
Is there a way of accomplishing that?
Upvotes: 2
Views: 213
Reputation: 26963
Not related to what you asked, but related to what i think you are trying to achieve; i would start looking at existing implementations how other libraries achieve integration between rigid body types, if only to have an idea what not to do.
Upvotes: -1
Reputation: 96281
Use a pure virtual function in the base class and override it in each derived class to return the appropriate value. This way you only have one copy of the constant, and each derived class defines it properly.
class Base
{
public:
virtual int get_constant0() const = 0;
};
class Derived0 : public Base
{
public:
virtual int get_constant0() const { return 5; }
};
class Derived1 : public Base
{
public:
virtual int get_constant0() const { return 42; }
};
Upvotes: 8