Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ typedef struct vs class

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;
like image 471
Sagi2313 Avatar asked Jan 24 '14 17:01

Sagi2313


1 Answers

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 structs 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.

like image 78
John Dibling Avatar answered Sep 28 '22 08:09

John Dibling