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


In what scenarios is it better to use a struct vs a class in C++?

8/28/2016 3:34:20 PM

Accepted Answer

Differences between a class and a struct in C++ are that structs have default public members and bases and classes have default private members and bases. Both classes and structs can have a mixture of public, protected and private members, can use inheritance and can have member functions.

I would recommend using structs as plain-old-data structures without any class-like features, and using classes as aggregate data structures with private data and member functions.

6/30/2018 6:23:37 AM

As everyone else notes there are really only two actual language differences:

  • struct defaults to public access and class defaults to private access.
  • When inheriting, struct defaults to public inheritance and class defaults to private inheritance. (Ironically, as with so many things in C++, the default is backwards: public inheritance is by far the more common choice, but people rarely declare structs just to save on typing the "public" keyword.

But the real difference in practice is between a class/struct that declares a constructor/destructor and one that doesn't. There are certain guarantees to a "plain-old-data" POD type, that no longer apply once you take over the class's construction. To keep this distinction clear, many people deliberately only use structs for POD types, and, if they are going to add any methods at all, use classes. The difference between the two fragments below is otherwise meaningless:

class X

  // ...

struct X
  // ...

(Incidentally, here's a thread with some good explanations about what "POD type" actually means: What are POD types in C++?)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow