In what scenarios is it better to use a struct
vs a class
in C++?
As everyone else notes there are really only two actual language differences:
struct
defaults to public access and class
defaults to private access.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 struct
s 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 struct
s for POD types, and, if they are going to add any methods at all, use class
es. The difference between the two fragments below is otherwise meaningless:
class X
{
public:
// ...
};
struct X
{
// ...
};
(Incidentally, here's a thread with some good explanations about what "POD type" actually means: What are POD types in C++?)