I am not very familiar with C++ , and while I am trying some test programms I came to a question regarding the best if I may say so way to define some primitive elements in C++ code.
Let's take a class that describes rectangles. It would create them, draw them , rotate, resize, etc... now in most cases we have to deal with points on the canvas. The rectangle its self is described by 2 points: Upper Left and Lower Right corner. Also in order to Rotate it, you need an angle, and a point(anchor point). Or maybe to move it you need a new anchor point for the given rectangle. I guess I made my point in using points . So what is more efficient ? to define this primitive point as a class or as a struct?
class cPoint
{
public:
int X;
int Y;
};
or
typedef struct
{
int X;
int Y;
}sPoint;
Niether are more efficient. On a technical level, there is no difference between a class
and a struct
aside from default visibility of members (public
in struct
, private
in class
) and default inheritance model (public
in struct
, private
in class
).
They typedef struct {} name
model is not idiomatic in C++. In fact, it's an abomination -- a holdover from C. Don't use this model. Use this struct name {};
instead. Using the typedef struct {} name;
model doesn't gain you anything in C++ (it was needed in C), and may cost you sojmething in terms of maintainability. For instance, it might be harder to grep
for typedef struct
declarations. But since it doesn't gain you anything by doing this, there's no compelling reason not to simply do struct name {};
in C++.
Aside from technical issues, the differences between struct
and class
are semantic ones. It is traditional and expected that objects declared as struct
s are simple objects which consist of only public:
data members (so-called PODs). If it has private
or protected
data, is expected to be derived from, or has any methods, it is declared as a class
.
This guideline is open to interpretation, and is just that -- a guideline. There is nothing to prevent you from declaring an abstract base class as a struct
, for example. However you may want to consider following this guideline in order to follow the Principle of Least Surprise, making your code easier to understand and maintain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With