Struct vs Class for simple data management

Question:
I have a data structure similar to this:

struct SPRITE  {    int x, y;    int jumping;};

This struct is easy to use in a game, because I can just assign a variable to be a “SPRITE” and then change its x, y, and jumping variables as I need. However, with a class, I would have to create methods to assign and get those values. Should I bother using classes for data structures like this? Since calling the methods (functions) will slow down my inner loop (this is for a game, obviously), I don’t know if it’s wise to convert this struct into a class or not?especially if I must add more variables to the class afterwards. I would be making tons of methods for it and then have a very cluttered SPRITE class.

Answer:
A couple of things.

First, although preferred, it is not necessary to use methods to change class variables. You could just as easily make those member variables public and access them directly. Moreover, using inline methods, you could make your methods every bit as fast as accessing the data members directly.

Beyond that, it really isn’t an issue between a structure and a class. In C++, the only real difference between the two is that one (structs) defaults to members being public, while the other (classes) defaults to members being private, and you can easily override even that.

So while I’d just go ahead and use classes with inline methods, it really doesn’t matter. Both C++ structs and classes can have methods and neither require them.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: