开发者

Making render method virtual?

I'm starting with C++ in more depth while building a simple 2d game engine. In my engine I have (or want to have) an "Abstract" GameEntity class, which carries the methods draw, update, and maybe position (x, y). I will add more stuff while it occurs to me.

Classes to inherit from GameEntity would be anything that could be drawn on screen (ParticleSystem, MovingSprite, StaticSprite, GuiMenu, etc...)

My problem is that to achieve that, I have declared GameEntity draw() and update() methods virtual:

virtual draw()=0;
virtual update()=0;

So 开发者_如何学CParticleSystem has it's own draw and MovingSprite also has it's own draw() (and update()).

I know virtual functions are expensive, or at least more expensive than regular methods. Do you think that what I'm doing is awful? Or too bad? If you do, I would really appreciate a better way to do this.

Thanks!


No, this isn't bad; the overhead isn't that significant (you might consult this answer to another question).

This is, for example, the general approach taken by OpenSceneGraph, an open source scene graph based on OpenGL. OSG has a Node class, from which all node types used in the scene graph are derived, and it uses a plethora of virtual functions.


The system I work on now uses virtual draw() and update() in the 3d layer tree; our performance bottlenecks are not in the virtual dispatch. I think your design is fine to start with; you can profile later if you think it's really bad. It's, what, a load and a jump?


Calling a virtual functions costs usually two pointer indirection more than a normal function call, so that's a really small overhead that should nearly never matter.

Also objects containing functions are the size of one pointer larger than objects without any virtual functions (they contain a pointer to the objects virtual function table). But if you don't plan on having really excessive amounts of small objects that also shouldn't matter.

For more details also see the C++ FAQ lite.

And to answer your question: I think it should work fine.


If you really need to handle multiple cases at runtime (and I think you do, in this case), it is best to use virtual functions. The compiler can probably optimize it as well or even better than an if-else statement, since virtual functions are something like a special case of if-else.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜