Search 74,992 tutors

Structs versus Classes

A struct is a datatype from the C programming language that encapsulates a number of different datatypes into a single object. This can be used to easily handle a set of values as a single "package", while also being able to access the individual members of the structure. One example of this may be a ContactInfo structure that contains a person's first name, last name, e-mail address, phone number, birthday, etc.

It's easy to see how this would later be extended into the notion of a "class", where the object could have methods defined to access the data or otherwise manipulate its contents, and even lend its functionality to extensions that "inherit" from that type. C++ added this capability to the "struct" while also providing the more appropriate "class" keyword that does mostly the same thing (with some minor differences, such as the default access for members and methods for a class is private while it is public for a struct, or in the way that one can use initializers for structs).

So when should you use a struct instead of a class when coding in C++ (or vice versa)? There are some differences of opinion on this, but I'll sum up my point of view with one simple tenet: If it looks like a class, make it a class. Don't put anything into a struct that wasn't part of the original C standard. If you want to define private members, or internal methods for the data access, or anything more complex than a simple data storage object or functor... then use a class. It will make your code more clear, and ensure compatibility if the C-style structs are in header files that may be used for building strictly C projects or may be built with different compilers.