views:

63

answers:

4

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 ParticleSystem 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!

+3  A: 

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.

James McNellis
Thanks for the answer, I happen to be using a SceneGraph for my game too, but it's a bit more simple and I only allow lists of subNodes in the scenes for now (don't need to support a tree structure of sub-nodes yet ).
Mr.Gando
+1  A: 

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.

int3
+2  A: 

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?

jeffamaphone
+2  A: 

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.

sth