In what scenarios is it better to use a struct
vs a class
in C++?
Both struct
and class
are the same under the hood though with different defaults as to visibility, struct
default is public and class
default is private. You can change either one to be the other with the appropriate use of private
and public
. They both allow inheritance, methods, constructors, destructors, and all the rest of the goodies of an object oriented language.
However one huge difference between the two is that struct
as a keyword is supported in C whereas class
is not. This means that one can use a struct
in an include file that can be #include
into either C++ or C so long as the struct
is a plain C style struct
and everything else in the include file is compatible with C, i.e. no C++ specific keywords such as private
, public
, no methods, no inheritance, etc. etc. etc.
A C style struct
can be used with other interfaces which support using C style struct
to carry data back and forth over the interface.
A C style struct
is a kind of template (not a C++ template but rather a pattern or stencil) that describes the layout of a memory area. Over the years interfaces usable from C and with C plug-ins (here's looking at you Java and Python and Visual Basic) have been created some of which work with C style struct
.