About the Author:

3.20 Structs and Unions in C++

Structs in C++

The C programming language had the concept of a structure, grouping data together to form a complex data type (for example: complex numbers, Person record). C++ extends this concept by allowing methods to be associated with this data, so for example in C we could:

Structs and Classes are very similar in C++; however, members in a struct are public by default and members in a class are private by default. The 'C' language only allows public member data within structs (there is no concept of private or protected in C).

We can construct any class from a struct and vice-verse. It is a question of style, however a class is more commonly used for a data structure that has associated methods.

Unions in C++

C++ has a structure that allows us to have different types of data within the same variable. A union is particularly memory efficient as it calculates the minimum amount of memory to store the largest element in the structure. Therefore, contained data overlaps in memory.