2

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?

1
  • Can you not make the function take the inertia tensor as an argument? You would then just create the static variable in each of your derived classes. You could arguably do this with traits, but I don't think it will save you much code. Commented Nov 8, 2011 at 17:49

2 Answers 2

8

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; }
};
Sign up to request clarification or add additional context in comments.

3 Comments

However, have you considered the price of virtual functions?
@XiaogeSu The price of the virtual function is this: One implementation per class and one additional pointer in the vtable. So there is no overhead per instance. Of course, you pay a little in performance for the required lookup and function call.
@cmaster I know this could be a problem. Of course, during the compile time the code could be optimized. I just want to point out that this makes an instant integer number, which can be stored directly into the assemble code, now requires a lookup and call.
-1

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.

ODE library

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.