In what scenarios is it better to use a struct
vs a class
in C++?
An advantage of struct
over class
is that it save one line of code, if adhering to "first public members, then private". In this light, I find the keyword class
useless.
Here is another reason for using only struct
and never class
. Some code style guidelines for C++ suggest using small letters for function macros, the rationale being that when the macro is converted to an inline function, the name shouldn't need to be changed. Same here. You have your nice C-style struct and one day, you find out you need to add a constructor, or some convenience method. Do you change it to a class
? Everywhere?
Distinguishing between struct
s and class
es is just too much hassle, getting into the way of doing what we should be doing - programming. Like so many of C++'s problems, it arises out of the strong desire for backwards compatability.