1

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.

Andrew
  • 3,393
  • 4
  • 25
  • 43
  • 3
    Some people like using `struct` only for POD types. I prefer saving the `public:` line. – chris Dec 22 '13 at 07:30

2 Answers2

2

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.

Preet Kukreti
  • 8,417
  • 28
  • 36
2

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();
  }
};
  • It was a demonstration class. I didn't provide extra code as to keep the length smaller than it could be. But yes, as it is written the class could have all of its members public. But what if I wanted my width and height to be greater than 1? Then a function would be satisfying. – Andrew Dec 22 '13 at 07:47
  • @Lemony-Andrew Then your box class could have an inner `Rect` that simply ensures the values are greater than 1. No need to repeat code. –  Dec 22 '13 at 07:49
  • Would you like to discuss this in the c++ chat room? I'd like to here more of what you have to say about this. *just curious on what you mean* – Andrew Dec 22 '13 at 07:55
  • Okay, I did some studying and I see what you mean. I'm not sure if I really like this for the current code, but it does seem very useful in the future.. This isn't exactly what my question was asking so that's why I mention the chat. But still, this is basically the same thing I had. You still need a get function, maybe not two (1 for w and 1 for h ) but you do need two classes for a class that could be created solely. + 1 for teaching me something new. – Andrew Dec 22 '13 at 08:09