Skip to content
Tutorials Center
My learning

Topics

Lesson 82 of 171 ยท Object-Oriented Programming

Structs, Aggregates and Unions

Learn C++ structs and aggregates - aggregate and designated initialization (C++20), structured bindings, unions and why std::variant is safer, and bit-fields.

Not every type needs constructors, private members and invariants. A 2D point, an RGB color, a row from a CSV file, a configuration block: these are just a few values bundled together, and the best way to write them in C++ is a plain struct with public members. C++ calls such simple types aggregates, and gives them special powers: you can initialize them member by member with braces, name the members you set with designated initializers (C++20), and unpack them into separate variables with structured bindings.

This lesson also covers two lower-level tools from C's heritage. A union stores several alternative members in the same memory, and a bit-field packs members into a few bits each. Both are useful for memory layouts and hardware formats, both are easy to misuse, and for unions there's a much safer modern replacement: std::variant. It builds on Classes and Objects.

struct versus class

In C++ a struct is a class. It can have member functions, constructors, private members, base classes and virtual functions. The only differences are the defaults:

struct class
default member access public private
default inheritance public private

The convention most codebases follow: use struct for passive data, a bundle of public values with no invariants to protect, and class when the type has private state and a set of operations that keep it consistent (see Access Specifiers and Encapsulation). A Temperature that must never drop below absolute zero is a class; a Pixel with x and y is a struct.

Aggregates and aggregate initialization

An aggregate is an array, or a class type that has:

  • no user-declared or inherited constructors,
  • no private or protected non-static data members,
  • no virtual functions,
  • no virtual, private or protected base classes.

Member functions, static members and public base classes are all allowed. For an aggregate, a braced list initializes the members in declaration order. Members you leave out get their default member initializer if they have one, and are otherwise value-initialized (zero for numbers, empty for strings).

C++ Aggregate initialization

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Every member of Color and Product has a default member initializer, and that's a good habit: a numeric member without one is left uninitialized when you create the object without braces (Color c;), just like a plain int. GCC's -Wextra also warns ("missing initializer for member") when a brace list skips a member that has no default member initializer. It does so even for a std::string or std::vector, which would be empty anyway; writing tags{} states "empty by default" and keeps the warning quiet.

Two more rules worth knowing:

  • Narrowing is an error in brace initialization: Color c{300, 0, 0}; doesn't compile, because 300 doesn't fit in an unsigned char. That's one reason braces are safer than = or () (see Variables).
  • C++20 allows parentheses for aggregates too: Color c(255, 0, 0);. Unlike braces, parentheses allow narrowing conversions, so braces remain the safer default.

Adding any constructor turns a struct into a non-aggregate, and from then on braces call the constructors instead. That's often a surprise when someone adds a "convenience" constructor and every {.name = ...} initialization in the codebase stops compiling.

Designated initializers (C++20)

With many members, positional initialization becomes hard to read: in Window w{800, 600, true, false, 2};, which bool is which? Designated initializers name each member:

C++ Designated initializers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

This is the closest thing C++ has to named arguments: a function takes an options struct, and callers set only what they care about. The rules are stricter than in C:

  • Designators must appear in declaration order, though you may skip members.
  • You can't mix designated and positional initializers in one list.
  • Only direct members can be designated: .size.width = 3 is not allowed. Write .size = {.width = 3} instead.
  • Arrays can't be designated: [2] = 5 is C, not C++.

GCC has supported designated initializers for years, and they are part of standard C++20, so they work with every current compiler.

Structured bindings

The opposite of aggregate initialization is unpacking. A structured binding declaration introduces several names at once, one per member, in declaration order:

C++ Unpacking structs with structured bindings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

You must bind all members (no skipping), and all non-static data members must be public and declared in the same class. auto [a, b] binds to a hidden copy of the object, auto& [a, b] to the object itself, and const auto& [a, b] is the usual choice in loops. Returning a small struct and unpacking it is the cleanest way to return several values from a function; see Returning Values.

Aggregates can also get comparison operators for free. Declare bool operator==(const Point&) const = default; (or auto operator<=>(const Point&) const = default; for ordering as well) and the compiler compares member by member. A defaulted comparison doesn't stop a struct from being an aggregate. Details are in Operator Overloading.

Unions

A union looks like a struct, but all its members share the same memory. Its size is the size of its largest member (plus alignment), and at any moment only one member, the one most recently written, is active. Reading any other member is undefined behavior in C++.

Because a union doesn't remember which member is active, you have to track it yourself, typically with an enum stored next to it. That combination is called a tagged union:

C++ A hand-made tagged union

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The union is 8 bytes (the double) instead of the 16 a struct of all three would need, and Value adds 4 bytes for the tag plus 4 bytes of padding. Space savings like this are why unions exist: interpreters, network packet parsers and embedded code use them heavily.

The dangers are equally clear:

  • Nothing stops you from reading the wrong member. Set kind = Int, write d, and the program has undefined behavior. The compiler won't help.
  • Type punning through a union is UB in C++. Writing a float and reading an int to see its bits is allowed in C, but not in C++. Use std::bit_cast (see RTTI, dynamic_cast and typeid).
  • Members with constructors and destructors are painful. If a union contains a std::string, the union's own constructor, destructor and copy operations are deleted. You must create and destroy the active member by hand with placement new and explicit destructor calls, and get it right on every path, including exceptions.

std::variant: the safe union

std::variant<A, B, C> (C++17, <variant>) is a tagged union written for you. It holds exactly one value of one of its alternative types, remembers which one, constructs and destroys it correctly (strings, vectors, anything), and refuses wrong-type access with an exception instead of undefined behavior.

C++ std::variant instead of a union

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

std::visit with an overload set is the variant's superpower: if you add a fourth alternative to Value and forget to handle it, the code stops compiling. Compare that with the switch on a hand-written tag, which compiles happily with a missing case. Prefer std::variant over a raw union in all application code; it's typically only as large as the union plus a small index. More on std::variant, std::visit and their friends in std::optional, std::variant, std::any and std::expected.

Bit-fields

A bit-field is a data member declared with a width in bits: unsigned month : 4; stores values 0 to 15 in just four bits. Adjacent bit-fields are packed into the same storage unit, which makes them handy for compact records and for mirroring hardware register or file-format layouts.

C++ Packing a date into 32 bits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The packed date takes 4 bytes instead of 12. The price:

  • Values silently wrap. Storing 18 in a 4-bit unsigned field keeps only the low bits, which gives 2. (With a constant like date.month = 18; GCC at least warns about the overflow.)
  • No addresses or references. &date.month doesn't compile, and neither does passing a bit-field to a function that takes a reference, which is why the example copies each field before printing.
  • The layout is implementation-defined: bit order, padding and whether a field can straddle storage units differ between compilers and platforms. Don't use bit-fields to parse files or network data that must be portable; use shifts and masks on fixed-width integers instead (see Bitwise Operators).
  • Reading or writing a bit-field compiles to shift-and-mask instructions, so it's slightly slower than a plain member.

Self-referential structs: linked nodes

A struct can't contain itself (it would need infinite size), but it can contain a pointer to its own type. A pointer has a fixed size, and inside the struct body the name is already declared, so the compiler accepts it. This is how linked lists, trees and graphs are built: each node holds some data and the address of the next node.

C++
struct Bad {
    int value;
    Bad inner;        // error: field has incomplete type 'Bad'
};

struct Good {
    int value;
    Good* next;       // fine: a pointer to the same type
};
C++ A linked chain of nodes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The loop prints 1 2 3, because each new node is pushed in front of the previous head. A Node is 16 bytes on a typical 64-bit platform: 4 bytes of int, 4 bytes of padding, and 8 bytes for the pointer. The compiler inserts padding so that every member sits at an address that's a multiple of its alignment, which alignof reports. Member order matters: Padded wastes space (24 bytes), while Reordered, with the same members largest first, takes 16. Memory Layout covers this in depth.

With raw pointers (Node* next) you must delete every node yourself; with unique_ptr it happens automatically, but a very long chain is destroyed recursively and can overflow the stack, so a real list class deletes iteratively. In practice, use std::list or std::forward_list, and write your own nodes only to learn or for specialised structures such as trees and graphs (Data Structures).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. struct Color { int r = 0, g = 0, b = 0, a = 255; }; Color c{10, 20}; What are c.b and c.a?

    Members left out of an aggregate's brace list get their default member initializers, so b is 0 and a is 255.
  2. 2. Which change stops struct Point { int x; int y; }; from being an aggregate?

    Any user-declared constructor makes the class a non-aggregate; braces then call constructors. Member functions, static members and defaulted comparisons are allowed in aggregates.
  3. 3. Given struct S { int a = 1; int b = 2; int c = 3; };, which line compiles?

    Designators must follow declaration order (you may skip members), can't be mixed with positional values, and array designators are C only.
  4. 4. A union has members int i and double d. The code writes d, then reads i. What does C++ say about that?

    Only the most recently written member of a union is active. Reading another one is undefined behavior in C++ (C allows it). Use std::bit_cast to look at bits.
  5. 5. What does std::get<int>(v) do when the std::variant v currently holds a std::string?

    std::variant checks which alternative is active. A wrong std::get throws; std::get_if returns nullptr instead.

Summary

  • A struct is a class whose members and bases are public by default. Use it for passive data without invariants.
  • An aggregate has no user-declared constructors, no private/protected data, no virtual functions or virtual/private bases. Brace lists initialize its members in order; omitted members use their default member initializers or are value-initialized.
  • Designated initializers ({.width = 1280}, C++20) name members, must follow declaration order and make options structs read like named arguments.
  • Structured bindings (auto [x, y] = p;) unpack public members; auto& binds to the original object.
  • A union overlaps its members in memory; only the active member may be read, and non-trivial members need manual lifetime management. Prefer std::variant, which tracks the active type and is checked by std::visit.
  • Bit-fields pack members into a few bits, but values wrap silently, they can't be referenced, and their layout isn't portable.

Next: Enumerations: enum and enum class, named constants with their own types.