2

Possible Duplicate:
When should you use a class vs a struct in C++?

When, if ever, should one use a STRUCT declaration rather than a CLASS declaration when writing a program using C++?

  1. Never !! ?
  2. Any thing...whichever makes one feel better?
Community
  • 1
  • 1
user1367292
  • 1,029
  • 2
  • 11
  • 13
  • 1
    Arghhhh... I hate when my name is put next to a vote to close reason which I didn't select. – Benjamin Lindley Dec 17 '12 at 17:54
  • 1
    Please read the details of struct and class here :https://stackoverflow.com/questions/54585/when-should-you-use-a-class-vs-a-struct-in-c/47168608#47168608 . Basically I use structs for data structures where the members can take any value, it's easier that way. – farhan Nov 07 '17 at 22:45

2 Answers2

6

Besides the default access level, a struct and a class are completely equivalent.

I find that the difference is mostly in the mind of a programmer - by convention, we typically use structs to put together small objects, without complex functionality - for example, a Point with just 3 members - the coordinates. POD-types.

On the other hand, we typically use classes to encompass somewhat bigger objects, with complex functionality and fairly large interface.

For example:

struct Point { 
   int x,y,z; 
};

class Shape{
   std::vector<Point> corners;
public:
   Shape(const std::vector<Point> corners);
   double getVolume();
   double getArea();
   bool   isConvex();
   //etc.
};
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
5

The only difference between the two is that by default struct are public while class members are private.

My rule is to use struct when I mean a clump of related data without any special semantics on reading/writing them. Use class when I intend to wrap the data in richer semantics (read methods) that are more meaningful, provide any needed protection, or implement something more abstract.

Doug T.
  • 64,223
  • 27
  • 138
  • 202