Compound Types in C++: Arrays, Pointers, References, Classes, Unions and Enums

The eight kinds of C++ compound type, from arrays and references to unions and pointers to members, each with a short, tested program.

Simple shapes combined into a row of identical squares, a case holding one of each shape and a tag pointing at a square, representing arrays, classes and pointers built from basic types

int and double are built into C++. int[4], int*, int&, std::string and int Point::* are not: each is made from other types, and the C++ standard calls every one of them a compound type. The compiler can tell you which is which: std::is_compound_v<int[4]> is true, and std::is_compound_v<int> is false. Knowing the eight kinds of compound type explains a lot of C++ behavior that otherwise looks arbitrary, such as why an array forgets its length when it is passed to a function, why there are no arrays of references and why reading the wrong member of a union is a bug.

This guide covers each kind of compound type with a short, complete program: arrays, pointers and references, classes, unions and std::variant, enumerations, functions and pointers to members. It then shows how compound types combine into declarations such as int (*)[3], and how to read them. Every program was compiled and tested with GCC and Clang (C++17 and C++20, warnings as errors) and with MSVC on Windows 11, and every output below is captured verbatim.

The Short Answer

What are compound types in C++? Types built from other types. The standard lists eight kinds: arrays, functions, pointers, references, classes (including structs), unions, enumerations and pointers to members.

What are the fundamental types? The types built into the language: void, std::nullptr_t, bool, the character types, the integer types and the floating-point types. Every other type is compound.

Is std::string a compound type? Yes. It is a class, and every class is a compound type, whether the language or the standard library defines it.

What Is a Compound Type in C++?

A compound type in C++ is any type that is not a fundamental type. Compound types are constructed from other types: an array of int, a pointer to double, a reference to a std::string, a class with members of several types, or a function type made from its parameter and return types. The standard library reports the category through std::is_compound.

The C++ standard divides every type into two groups. The fundamental types are built in. The compound types are built from them, and from each other. cppreference’s page on types lists the full classification, with the type trait that tests each category.

Kind of compound typeExampleBuilt from
Arrayint[4]An element type and a length
Functionint(int, int)Parameter types and a return type
Pointerint*The type it points to
Referenceint&, int&&The type it refers to
Class (including struct)Point, std::stringIts members’ types
UnionNumberIts members’ types, sharing one block of memory
Enumerationenum class ColorAn underlying integer type
Pointer to memberint Point::*A class and one of its members’ types
C++ types: fundamental and compound Every type is one or the other. The categories below are the ones type_census.cpp reports. Fundamental built into the language void std::nullptr_t bool characters char, wchar_t, char16_t, char32_t integers short, int, long, long long, unsigned floating point float, double, long double is_compound_v<T>: false Arrays int[4] N elements of one type Functions int(int, int) parameter and return types Pointers int* address of an object or function References int& int&& another name for an object Classes struct Point, std::string members of any types Unions union Number members share the same bytes Enumerations enum class Color named integer constants Pointers to members int Point::* a member of a class Compound types are built from other types, and they combine: int* [3] array of 3 pointers int (*)[3] pointer to an array of 3 int (*)(double) pointer to a function taking double, returning int
Figure 1: Every C++ type is fundamental or compound. The eight compound kinds on the right are built from other types and can be combined, as the declarations at the bottom show.

You do not have to memorize the table. The type traits in <type_traits> answer the same questions at compile time, and this program asks them about one type of each kind:

// type_census.cpp - asks the compiler which category each type belongs to.
// The type traits in <type_traits> answer the same questions the C++
// standard uses to divide types into fundamental and compound.
#include <cstddef>
#include <iomanip>
#include <iostream>
#include <string>
#include <type_traits>

struct Point { int x; int y; };

class Account {
public:
    double balance() const { return balance_; }
private:
    double balance_ = 0;
};

union Number { int i; float f; };

enum class Color { red, green, blue };

template <typename T>
const char* category()
{
    if constexpr (std::is_fundamental_v<T>) return "fundamental";
    else if constexpr (std::is_array_v<T>) return "array";
    else if constexpr (std::is_function_v<T>) return "function";
    else if constexpr (std::is_lvalue_reference_v<T>) return "lvalue reference";
    else if constexpr (std::is_rvalue_reference_v<T>) return "rvalue reference";
    else if constexpr (std::is_member_object_pointer_v<T>) return "pointer to data member";
    else if constexpr (std::is_member_function_pointer_v<T>) return "pointer to member function";
    else if constexpr (std::is_pointer_v<T>) return "pointer";
    else if constexpr (std::is_enum_v<T>) return "enumeration";
    else if constexpr (std::is_union_v<T>) return "union";
    else if constexpr (std::is_class_v<T>) return "class";
    else return "unknown";
}

template <typename T>
void row(const char* name)
{
    std::cout << std::left << std::setw(30) << name
              << std::setw(13) << (std::is_compound_v<T> ? "compound" : "fundamental")
              << category<T>() << '\n';
}

int main()
{
    std::cout << std::left << std::setw(30) << "type" << std::setw(13) << "kind" << "category\n";
    row<int>("int");
    row<double>("double");
    row<bool>("bool");
    row<void>("void");
    row<std::nullptr_t>("std::nullptr_t");
    row<int[4]>("int[4]");
    row<int(int, int)>("int(int, int)");
    row<int*>("int*");
    row<int&>("int&");
    row<int&&>("int&&");
    row<Point>("Point (struct)");
    row<Account>("Account (class)");
    row<Number>("Number (union)");
    row<Color>("Color (enum class)");
    row<int Point::*>("int Point::*");
    row<double (Account::*)() const>("double (Account::*)() const");
    row<std::string>("std::string");
}

Output:

type                          kind         category
int                           fundamental  fundamental
double                        fundamental  fundamental
bool                          fundamental  fundamental
void                          fundamental  fundamental
std::nullptr_t                fundamental  fundamental
int[4]                        compound     array
int(int, int)                 compound     function
int*                          compound     pointer
int&                          compound     lvalue reference
int&&                         compound     rvalue reference
Point (struct)                compound     class
Account (class)               compound     class
Number (union)                compound     union
Color (enum class)            compound     enumeration
int Point::*                  compound     pointer to data member
double (Account::*)() const   compound     pointer to member function
std::string                   compound     class

Three results are worth noticing:

  • void and std::nullptr_t are fundamental, even though neither holds a number.
  • A struct is a class. Point and Account land in the same category; the only difference between struct and class is the default access of members and base classes.
  • Library types are compound too. std::string is reported exactly like Point, because to the language it is just another class.

Arrays: A Type That Includes Its Length

An array type has two parts: the element type and the number of elements. double[4] and double[5] are different types. That length is easy to lose, because an array converts to a pointer to its first element almost everywhere it is used, including when it is passed to a function:

// arrays.cpp - an array's type includes its length. The length is lost when
// the array decays to a pointer, and kept by a reference to the array or by
// std::array.
#include <array>
#include <cstddef>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <type_traits>

// Receives only an address, so the caller must pass the count separately.
double total_by_pointer(const double* prices, std::size_t count)
{
    double sum = 0;
    for (std::size_t i = 0; i < count; ++i)
        sum += prices[i];
    return sum;
}

// A reference to an array keeps the length in the type: N is deduced.
template <std::size_t N>
double total_by_reference(const double (&prices)[N])
{
    double sum = 0;
    for (double p : prices)
        sum += p;
    return sum;
}

// std::array is a class wrapping a C array: it can be passed, copied and
// returned like any other value, and it always knows its size.
double total_of(const std::array<double, 4>& basket)
{
    double sum = 0;
    for (double p : basket)
        sum += p;
    return sum;
}

int main()
{
    std::cout << std::fixed << std::setprecision(2);

    double prices[] = {19.99, 5.49, 3.75, 12.00};
    static_assert(std::is_same_v<decltype(prices), double[4]>, "the length is part of the type");
    std::cout << "sizeof(prices) = " << sizeof(prices) << " bytes, "
              << std::size(prices) << " elements\n";

    const double* first = prices;   // the array decays to a pointer to its first element
    std::cout << "sizeof(first) = " << sizeof(first) << " bytes: only the address is left\n";

    std::cout << "total by pointer and count:  " << total_by_pointer(prices, std::size(prices)) << '\n';
    std::cout << "total by reference to array: " << total_by_reference(prices) << '\n';

    std::array<double, 4> basket{19.99, 5.49, 3.75, 12.00};
    std::array<double, 4> copy = basket;    // a C array cannot be copied with =
    copy[0] = 0;
    std::cout << "std::array: size() = " << basket.size() << ", total = " << total_of(basket)
              << ", copy total = " << total_of(copy) << '\n';
}

Output:

sizeof(prices) = 32 bytes, 4 elements
sizeof(first) = 8 bytes: only the address is left
total by pointer and count:  41.23
total by reference to array: 41.23
std::array: size() = 4, total = 41.23, copy total = 21.24

The first two lines show the conversion. sizeof(prices) is 32 bytes, four doubles, but after const double* first = prices; only an 8-byte address is left. The sizes are from a 64-bit build; a 32-bit build prints 4 for the pointer. A function that receives the pointer cannot recover the length, which is why total_by_pointer needs a separate count parameter, and why passing the wrong count is a classic out-of-bounds bug.

There are two ways to keep the length:

  • A reference to an array keeps the whole type, const double (&)[4]. The template parameter N is deduced from it, so total_by_reference(prices) needs no count.
  • std::array<double, 4> is a class that wraps an array. It can be copied with = (a plain array cannot) and returned from a function, and it always knows its size(). Modifying copy[0] left basket unchanged, as the two totals show.

For new code, prefer std::array for a fixed size and std::vector for a variable one. Arrays in C and C++ covers the memory layout and multidimensional arrays in more depth.

Pointers and References

A pointer is an object that stores an address. It can be null, and it can be changed to point to something else. A reference is another name for an existing object. It must be bound when it is created and never changes what it refers to:

// pointers_references.cpp - a pointer is an object holding an address; it can
// be null and can be pointed somewhere else. A reference is another name for
// an existing object; it must be bound when created and never changes target.
#include <iostream>

void add_bonus(int* score)          // the caller passes an address, which may be null
{
    if (score != nullptr)
        *score += 10;
}

void add_bonus(int& score)          // the caller passes an object; no null check needed
{
    score += 10;
}

int main()
{
    int alice = 50;
    int bob = 70;

    int* p = &alice;
    *p += 1;                         // changes alice through the pointer
    p = &bob;                        // the pointer now points to bob
    *p += 1;
    std::cout << "after pointer:   alice = " << alice << ", bob = " << bob << '\n';

    int& r = alice;                  // r is another name for alice, for good
    r = bob;                         // copies bob's value into alice; r still names alice
    r += 1;
    std::cout << "after reference: alice = " << alice << ", bob = " << bob << '\n';

    add_bonus(&bob);
    add_bonus(nullptr);              // allowed, and the function must check
    add_bonus(alice);
    std::cout << "after bonuses:   alice = " << alice << ", bob = " << bob << '\n';

    const int* read_only = &alice;   // pointer to const: cannot change alice through it
    int* const fixed = &bob;         // const pointer: cannot point elsewhere
    *fixed += 5;                     // allowed: the int it points to is not const
    std::cout << "read_only -> " << *read_only;
    read_only = &bob;                // allowed: the pointer itself is not const
    std::cout << ", re-pointed -> " << *read_only << ", fixed -> " << *fixed << '\n';
}

Output:

after pointer:   alice = 51, bob = 71
after reference: alice = 72, bob = 71
after bonuses:   alice = 82, bob = 81
read_only -> 82, re-pointed -> 86, fixed -> 86

The second line is the one that surprises people. r = bob; does not make r refer to bob. It assigns bob‘s value (71) to alice, because r is alice, and then r += 1 makes alice 72. There is no syntax for re-pointing a reference.

That difference decides which one a function should take. add_bonus(int*) accepts nullptr, so it has to check. add_bonus(int&) cannot receive a null reference, so it needs no check. A good default is to use a reference when an object is required, and a pointer when “no object” is a valid input.

The last line shows the two places const can go. const int* protects the int: read_only cannot change alice, but it can be pointed at bob. int* const protects the pointer: fixed can change bob but cannot point anywhere else. Read the declaration from right to left: “fixed is a const pointer to int“.

Because a reference is not an object, two declarations that look reasonable do not compile. The repository’s tests build both and check that the compiler rejects them:

int& refs[2] = {x, y};   // an array of references
int& r;                  // a reference bound to nothing
GCC:   error: declaration of 'refs' as array of references
Clang: error: 'refs' declared as array of references of type 'int &'
GCC:   error: 'r' declared as reference but not initialized
Clang: error: declaration of reference variable 'r' requires an initializer

To store references in an array or a container, use pointers or std::reference_wrapper. Pointers, pointer arithmetic and const-correctness are covered in more depth in pointers in C++, and owning pointers in smart pointers in modern C++.

Classes and Structs

A class is the most flexible compound type: its members can be of any types, including other compound types, and it adds member functions, access control, constructors and destructors. struct and class declare the same kind of type. The only differences are the defaults:

Featurestructclass
Default member accesspublicprivate
Default base-class accesspublicprivate
Can have member functions, constructors, base classesYesYes
What std::is_class_v reportstruetrue

By convention, struct is used for simple groups of public data, like Point, and class for types that protect their data behind member functions, like Account. The Employee struct in the pointers-to-members section below is a typical struct. How classes are designed, from constructors to static members, is the subject of classes in object-oriented programming.

Unions, Tagged Unions and std::variant

A union is a class whose members all start at the same address, so it is only as large as its largest member, and only one member holds a value at a time. The union does not record which one. Writing one member and then reading another is undefined behavior in C++, although C allows it, a difference that catches code moving between the two languages (union in C covers the C rules). To look at the bytes of a float, copy them with std::memcpy (or use C++20’s std::bit_cast) instead:

// unions_variant.cpp - a union stores one of several members in the same
// bytes and does not record which one. A tagged union adds that record by
// hand; std::variant does it automatically and checks every access.
#include <cstdint>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <string>
#include <type_traits>
#include <variant>
#include <vector>

union Number {
    std::int32_t i;
    float f;
};

// A tagged union: the enum says which member of the union is active.
struct Setting {
    enum class Kind { integer, real } kind;
    union {
        int i;
        double d;
    } value;
};

void print(const Setting& s)
{
    switch (s.kind) {
    case Setting::Kind::integer: std::cout << "integer " << s.value.i << '\n'; break;
    case Setting::Kind::real:    std::cout << "real " << s.value.d << '\n'; break;
    }
}

// The same idea with std::variant: the type remembers which alternative it holds.
using Value = std::variant<int, double, std::string>;

struct Describe {
    void operator()(int v) const { std::cout << "int " << v << '\n'; }
    void operator()(double v) const { std::cout << "double " << v << '\n'; }
    void operator()(const std::string& v) const { std::cout << "string \"" << v << "\"\n"; }
};

int main()
{
    std::cout << "sizeof(Number) = " << sizeof(Number) << " (members share the same 4 bytes)\n";

    Number n;
    n.f = 1.0f;     // f is now the active member; reading n.i would be undefined behavior

    // To see a float's bits, copy them into an integer instead of reading the
    // inactive member. (C++20 adds std::bit_cast for the same job.)
    std::uint32_t bits = 0;
    static_assert(sizeof bits == sizeof n.f);
    std::memcpy(&bits, &n.f, sizeof bits);
    std::cout << "bits of 1.0f = 0x" << std::hex << std::setw(8) << std::setfill('0') << bits
              << std::dec << std::setfill(' ') << '\n';

    Setting timeout{Setting::Kind::integer, {}};
    timeout.value.i = 30;
    Setting ratio{Setting::Kind::real, {}};
    ratio.value.d = 0.75;
    print(timeout);
    print(ratio);

    std::vector<Value> values{42, 2.5, std::string("blue")};
    for (const Value& v : values)
        std::visit(Describe{}, v);

    Value v = 2.5;
    std::cout << "holds double? " << std::boolalpha << std::holds_alternative<double>(v) << '\n';
    try {
        std::cout << std::get<int>(v) << '\n';      // wrong alternative
    } catch (const std::bad_variant_access&) {
        std::cout << "std::get<int> on a double: std::bad_variant_access\n";
    }
}

Output:

sizeof(Number) = 4 (members share the same 4 bytes)
bits of 1.0f = 0x3f800000
integer 30
real 0.75
int 42
double 2.5
string "blue"
holds double? true
std::get<int> on a double: std::bad_variant_access

The program shows three levels of safety:

  • A plain union (Number) is 4 bytes for an int and a float, and nothing stops you from reading the wrong member. 0x3f800000 is the IEEE 754 bit pattern of 1.0, obtained with memcpy, which is well defined.
  • A tagged union (Setting) stores an enum next to the union to record which member is active, and every reader must check it. This is the classic pattern in C and in older C++ code.
  • std::variant (C++17) is a tagged union managed by the library. It records the active alternative, and std::visit calls the right overload of Describe. Asking for the wrong type with std::get<int> throws std::bad_variant_access instead of returning garbage.

Use std::variant in new C++ code, and keep raw unions for memory-mapped hardware, binary formats and interfaces with C. cppreference’s std::variant reference lists the full interface.

Enumerations

An enumeration is a type whose values are named integer constants. C++ has two kinds:

  • Plain enum, inherited from C: its names are visible in the surrounding scope and convert to int automatically.
  • enum class (C++11): its names are scoped (Color::red) and never convert to int without a static_cast. Its underlying type can be chosen, as in enum class Color : std::uint8_t.

Color in the type census is an enum class, and std::is_enum_v reports it as an enumeration, not as an integer. Prefer enum class in C++. Enum in C covers enums in depth, including a section on how C++ enum class differs from C’s enums.

Pointers to Members

A pointer to member names a member of a class, not a member of one object. &Employee::age means “the age member of any Employee“. Applied to an object with .* (or ->* through a pointer), it selects that member of that object. This lets one function work on whichever field it is given:

// member_pointers.cpp - a pointer to member names a member of a class, not a
// member of one object. Applied to an object with .* or ->*, it selects that
// member. Here one sort function sorts by whichever field it is given.
#include <algorithm>
#include <functional>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>

struct Employee {
    std::string name;
    int age;
    double salary;

    double monthly() const { return salary / 12; }
};

template <typename T>
void sort_by(std::vector<Employee>& staff, T Employee::*field)
{
    std::sort(staff.begin(), staff.end(),
              [field](const Employee& a, const Employee& b) { return a.*field < b.*field; });
}

void print(const char* title, const std::vector<Employee>& staff)
{
    std::cout << title << ':';
    for (const Employee& e : staff)
        std::cout << ' ' << e.name;
    std::cout << '\n';
}

int main()
{
    std::vector<Employee> staff{
        {"Maya", 41, 98000}, {"Omar", 29, 87000}, {"Lena", 35, 121000}, {"Ravi", 52, 76000}};

    sort_by(staff, &Employee::name);
    print("by name  ", staff);
    sort_by(staff, &Employee::age);
    print("by age   ", staff);
    sort_by(staff, &Employee::salary);
    print("by salary", staff);

    int Employee::*field = &Employee::age;          // pointer to data member
    double (Employee::*pay)() const = &Employee::monthly;   // pointer to member function

    const Employee& first = staff.front();
    std::cout << std::fixed << std::setprecision(2);
    std::cout << first.name << ": age " << first.*field << ", monthly " << (first.*pay)()
              << ", via std::invoke " << std::invoke(pay, first) << '\n';
}

Output:

by name  : Lena Maya Omar Ravi
by age   : Omar Lena Maya Ravi
by salary: Ravi Omar Maya Lena
Ravi: age 52, monthly 6333.33, via std::invoke 6333.33

sort_by is written once and sorts by a std::string, an int or a double, because T Employee::*field deduces the member’s type. The same idea works for member functions: double (Employee::*)() const points to monthly, and (first.*pay)() calls it. The parentheses are required, because () binds more tightly than .*. std::invoke(pay, first) calls it without the awkward syntax, and it is how the standard library itself calls member pointers. Pointers to members are rarer than the other compound types, but they appear in sorting and projection code, in serialization libraries and in signal-and-slot frameworks.

Combining Compound Types: Reading Declarations

Compound types are built from other types, including other compound types. That is where C++ declarations get hard to read. The rule that works: start at the name, read right (arrays and function parameters), then left (pointers and references), and let parentheses change the order.

// declarations.cpp - compound types combine. Read a declaration from the name
// outward: right first (arrays, function parameters), then left (pointers,
// references), and parentheses change the order.
#include <cstddef>
#include <iostream>
#include <type_traits>

int twice(double x) { return static_cast<int>(x * 2); }

int counter = 0;
int& next_counter() { return ++counter; }

int main()
{
    int a = 1, b = 2, c = 3;
    int row[3] = {7, 8, 9};

    int* pointers[3] = {&a, &b, &c};   // array of 3 pointers to int
    int (*to_row)[3] = &row;           // pointer to an array of 3 int
    int (*fn)(double) = &twice;        // pointer to a function taking double, returning int
    int& (*counter_fn)() = &next_counter;   // pointer to a function returning int&

    static_assert(std::is_same_v<decltype(pointers), int* [3]>);
    static_assert(std::is_same_v<decltype(to_row), int (*)[3]>);
    static_assert(std::is_same_v<decltype(fn), int (*)(double)>);

    std::cout << "sizeof(pointers) = " << sizeof(pointers) << " (three pointers)\n";
    std::cout << "sizeof(to_row)   = " << sizeof(to_row) << " (one pointer)\n";
    std::cout << "*pointers[1] = " << *pointers[1] << ", (*to_row)[1] = " << (*to_row)[1] << '\n';
    std::cout << "fn(2.6) = " << fn(2.6) << '\n';
    counter_fn() += 100;                 // the call returns a reference, so it can be assigned
    std::cout << "counter = " << counter << '\n';

    // Type aliases make the same types readable.
    using Row = int[3];
    using Transform = int (*)(double);
    Row* same_as_to_row = &row;
    Transform same_as_fn = twice;       // a function name decays to a pointer, like an array
    static_assert(std::is_same_v<Row*, decltype(to_row)>);
    std::cout << "via aliases: " << (*same_as_to_row)[2] << ", " << same_as_fn(1.0) << '\n';
}

Output:

sizeof(pointers) = 24 (three pointers)
sizeof(to_row)   = 8 (one pointer)
*pointers[1] = 2, (*to_row)[1] = 8
fn(2.6) = 5
counter = 101
via aliases: 9, 2

Applying the rule:

  • int* pointers[3]: pointers is an array of 3 (right), of pointers to int (left). It is 24 bytes: three 8-byte pointers.
  • int (*to_row)[3]: the parentheses come first, so to_row is a pointer (left), to an array of 3 int (right). It is one 8-byte pointer.
  • int (*fn)(double): fn is a pointer to a function taking a double and returning int.
  • int& (*counter_fn)(): a pointer to a function returning int&. Because the call returns a reference, counter_fn() += 100 changes counter itself, which ends at 101.

The static_assert lines are the compiler confirming each reading; if one were wrong, the program would not build. Functions are compound types too, which is why fn has a function type inside its pointer type. A function name converts to a pointer to the function, just as an array name converts to a pointer to its first element, which is why Transform same_as_fn = twice; needs no &. How functions themselves are declared and called is covered in functions in C++.

In real code, name the parts. using Row = int[3]; and using Transform = int (*)(double); turn the hardest declarations into Row* and Transform, and std::function<int(double)> is often clearer still for callbacks.

Common Mistakes with Compound Types

  • Using sizeof on an array parameter. A parameter written double prices[] is a pointer, so sizeof(prices) inside the function gives the pointer’s size. GCC and Clang both warn about this by default (-Wsizeof-array-argument). Pass a reference to the array, a std::array, or a std::span (C++20) instead.
  • Reading the inactive member of a union. It compiles and often appears to work, but it is undefined behavior in C++. The repository’s pitfalls/inactive_member.cpp does exactly this: it builds without a warning under -Wall -Wextra -pedantic, and AddressSanitizer and UndefinedBehaviorSanitizer stay silent when it runs, so no tool will catch it for you. Use std::variant, or memcpy to reinterpret bytes.
  • Expecting r = other; to rebind a reference. It assigns through the reference. If the target must change, use a pointer.
  • Returning a pointer or reference to a local variable. The local is destroyed when the function returns, and the pointer or reference dangles. GCC (-Wreturn-local-addr) and Clang (-Wreturn-stack-address) warn about the direct case by default. When the reference goes through a local variable first (int& r = x; return r;), Clang still warns, but GCC 13 warns only in an optimized build (-O2), so treat the warnings as a safety net, not a guarantee.
  • Forgetting the parentheses in a declaration. int* p[3] and int (*p)[3] are different types. When in doubt, use a using alias.

Key Takeaways

  • Every C++ type is fundamental or compound. Fundamental types are built in; compound types are built from other types, and std::is_compound_v tells them apart.
  • There are eight kinds of compound type: arrays, functions, pointers, references, classes, unions, enumerations and pointers to members.
  • An array’s length is part of its type, and it is lost when the array decays to a pointer. Use a reference to the array, std::array or std::span to keep it.
  • A reference is another name for an object. It must be initialized, cannot be null and cannot be re-pointed, so there are no arrays of references.
  • A union does not know which member it holds. std::variant does, and it checks every access.
  • Compound types combine. Read declarations from the name outward, right then left, and use using aliases to keep them readable.

Conclusion

Compound types are how C++ builds everything beyond a single number: an array is a type plus a count, a pointer is a type plus an address, a class is a set of types under one name. Most of the language’s sharp edges, from array decay to dangling references to unions without a tag, come from the rules of one particular compound type, and knowing which kind you are holding is the quickest way to predict how it behaves.

For more C++ fundamentals and the rest of the language, see the C++ section.

Source Code and Tests

compound-types workflow status

All programs on this page are in the basics/compound-types directory of the MYCPLUS C++ examples repository.

Build and test:

cmake -S . -B build
cmake --build build
ctest --test-dir build --output-on-failure

What the build checks.

  • Compilers: GCC and Clang under C++17 and C++20 with -Wall -Wextra -pedantic -Werror, and MSVC with /W4 /WX /permissive-.
  • Output: each of the six programs prints exactly the output shown on this page.
  • Compile failures: the array of references and the unbound reference must fail to build, with a compiler message that names the problem. A build that fails for any other reason does not count as a pass.
  • Sanitizers: on Linux, every test also runs under AddressSanitizer and UndefinedBehaviorSanitizer.

What I Verified

Everything in the Ubuntu column was run for this article on Ubuntu 24.04 (x86-64, GCC 13.3, Clang 18.1, CMake 3.28). The Windows column comes from run_all.ps1 in the repository, run on Windows 11 (build 26300) with MSVC.

CheckUbuntu 24.04Windows 11
Build with warnings as errorsGCC and Clang, C++17 and C++20: passedMSVC /W4 /WX /permissive-, C++17 and C++20: passed
CTest: 6 output comparisons and 2 programs that must not compile8 of 8 in all four configurations8 of 8 in C++17 and in C++20
AddressSanitizer and UndefinedBehaviorSanitizer, every test8 of 8, cleanNot applicable
Valgrind memcheck, every programNo errors, no leaksNot applicable
Deliberate mistakes: a compile-fail program that compiles, one that fails for an unrelated reason, a changed expected outputAll three caughtNot run

Not covered: 32-bit builds (pointer sizes would print 4), macOS and compilers older than GCC 13 and Clang 18.

Scroll to Top