开发者

Is there a slicing problem with this inheritance structure?

I am doing some game design, and decided that I want a data centric model... one "game data" object which gets passed from subsystem to subsystem, and knows itself how it should be drawn, how physics should operate on itself, how inputs from the user will affect it etc.

So I started out with "Listener"ish objects like "BaseRenderer" "BaseInputHandler" etc:

class BaseRenderer
{
public:
    virtual void Render(BITMAP *b) = 0;
};

class BaseInputHandler
{
public:
    virtual int TakeInputs() = 0;
};

And created a "GameData" object which inherits from these...

class GameData : public BaseRenderer, public BaseInputHandler, public BaseCalculator
{
public:
    /* Virtual Overwrites: (each child of GameData will need to overwrite these!) 
    void Render(BITMAP *b);
    int TakeInputs();
    void Calculate();*/
};

And then each subsystem has a singleton which will execute the various operations (render, take inputs, etc) on the game data...

GameData gd; // Or inherited from GameData...
Input::System().Init();
...
while(loop) {
    loop &= !(Input::System().GetInputs(&gd));
    ...
}

Is this a valid and sensible way to do inheritance? The reason I ask is because I am getting obscure runtime crashes... Not allocating any dynamic memory. Last night I got a crash from adding 2 member functions to GameData (virtual or not virtual) and then it went away when I added them slowly (first 1 non-virtual, then 1 virtual, then 2 non-virtual etc).

I read so开发者_高级运维mething on SO (can't remember where it was now) about inheritance and slicing. I didn't really get it, but am I doing something dangerous with my inheritance which is causing intermittent runtime bugs?

Or should I look at my timing code which is using QueryPerformanceCounter?

MinGW + allegro


Slicing occurs when you pass by value. If your base types are abstract (have pure virtual functions), slicing cannot occur; the compiler will complain instead. (Slicing occurs when an object is copied, but only the base class is copied.)

As long as you're not trying to use value semantics (pass by value, etc.), your hierarchy should be fine; most of the time, in such cases, I'll forbid copy systematically, by having everything derive from boost::noncopyable, but this isn't really necessary, as long as all of the bases are abstract.

One other special issue to pay attention to is that all explicit conversions are on pointers or references (not values), and that they use the new style casts (dynamic_cast, in general). When multiple inheritance is involved, an C-style cast can accidentally end up being a reinterpret_cast, and the code will do strange things after that.

In addition, of course, the usual issues apply: no dangling pointers, etc. (You say you have no dynamic allocation. I find this surprising if you have polymorphic types, which generally shouldn't support copy.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜