Let's see equivalent examples, let's talk about the philosophy later...
struct Vector { double x,y; }; class Vector { public: double x,y; };
and
class Vector { public: Vector(double x_, double _y); Vector& SetXY(double x_,double y_); double GetX() const; double GetY() const; //... private: double x,y; }; struct Vector { Vector(double x_, double _y); Vector& SetXY(double x_,double y_); double GetX() const; double GetY() const; //... private: double x,y; };
In my opinion class's default visibility is not very useful because we used to start the class definition with the public members to ease the interpretation of it for the users of our class.
The big difference is in the intent of the declaration. If we want to create a composite behavior-less data unit that is passed around, then we should use the struct keyword so the reader will know what's going on. If you want to create an object which fulfills an abstract concept and has a behavior, then you should define a class.
IMPORTANT: If you use class you should really take care about the basic requirements like hiding data members (making them private or protected in order to maintain
principle of local responsibility), providing type-invariant safe public methods, disabling
copy semanticsif not needed explicitly, and so on ...
thanks for that...
ReplyDeleteI've been looking at c++ struct as a weird thing, until reading this, then checked syntax description at cppreference... it has inheritance too...
What you think why struct has changed to this from the one we knowed in C?
I think the 'class' keyword which they created was able to "emulate" the old style 'struct' which gave the idea that they could be the same...
ReplyDeleteI wonder... I suspect that this was not a pure accident but some kind of goal. The C++ inventors wanted to keep and train the existing C community.