CISC 3142
Programming Paradigms in C++
Part II: Basic Facilities
Chapter 8 — Structures, Unions, and Enumerations
Reading from the Text
Chapter 8 — Structures, Unions, and Enumerations
Skip §§ 8.3-8.4
If you've learned abvout enumerations in Java, you should be able to read § 8.4
Overview
This chapter deals with the low-level user-defined data types in the language — all (with the exception of enum classes) derived from
C. We will only mention structures, and even that only briefly.
Topics
Structures
a structure is a heterogeneousaggregate of elements, usually called fields.
heterogeneous: different types (as opposed to an array which is homogeneous)
aggregate: collection of items
struct Person {
char *last_name;
char *first_name;
int age;
bool married;
};
Structures and Classes
Although, the notion of a structure — as derived from C — is an aggregate of data, in C++ structures can also
have member functions
The sole difference between a structure and a class is that the members of a structure are public by default
(whereas they are private by default in a class).
structures can thus have constructors and member functions, just like classes
a common convention is to use structures when one only wishes to have data, which is then declared (often implicitly) public
and no member functions
Stroustrup employs the term POD (plain old data) for something similar to this
Advice
[1] When compactness of data is important, lay out structure data members with larger members before smaller ones; §8.2.1.
[2] Use bit-fields to represent hardware-imposed data layouts; §8.2.7.
[3] Don't naively try to optimize memory consumption by packing several values into a single byte; §8.2.7.
[4] Use unions to save space (represent alternatives) and never for type conversion; §8.3.
[5] Use enumerations to represent sets of named constants; §8.4.
[6] Prefer enum classes over 'plain' enums to minimize surprises; §8.4.
[7] Define operations on enumerations for safe and simple use; §8.4.1.