Default security parameter in classes

244 views Asked by At

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.

2

There are 2 answers

0
Preet Kukreti On BEST ANSWER

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.

4
AudioBubble On

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();
  }
};