Domanda

I have noticed in a large amount of code that people declare their classes public before writing code into it. Is this a preference or is there more meaning to it? It seems kind of superfluous to me being that struct's default parameter is public and does exactly what a class does (as I have read).

code example

class box
{
public:
void setParam( int x, int y) { . . . }
int getWidth(){ . . . }
int getHeight(){ . . . }
private:
int width, height;
}

Could be done without declaring it public in a struct.

È stato utile?

Soluzione

Generally its a matter of convention/semantics than it is because of a technical reason.

The rationale is usually that structs are reserved for POD usage, helper data structures, "data payload"s, functors etc. Whereas classes are for types that encapsulate non-trivial operations that usually have to respect some type of class invariant.

Altri suggerimenti

A struct that looks like your class might look like this:

struct Rect
{
 int x, y, w, h;
};

It instantly conveys to the reader that it's intended to be an simple POD type with no bells and whistles. On the other hand, your example has accessor methods which seem superfluous if all they intend to do is get and set your private members. You might as well make them public.


Example of my comment:

class box
{
  Rect _surface;
public:
  explicit box(Rect surface) : _surface(surface)
  {
    if (surface.w <= 0 || surface.h <= 0) throw bad_dimensions();
  }
};
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top