Thursday, November 19, 2026
HomeC ProgrammingCompound Sorts in C++: Arrays, Pointers, References, Unions

Compound Sorts in C++: Arrays, Pointers, References, Unions


int and double are constructed into C++. int[4], int*, int&, std::string and int Level::* usually are not: every is constructed from different sorts, and the C++ customary calls each one in all them a compound kind. The compiler can let you know which is which: std::is_compound_v<int[4]> is true, and std::is_compound_v<int> is false. Figuring out the eight sorts of compound kind explains numerous C++ conduct that in any other case appears to be like arbitrary, resembling why an array forgets its size when it’s handed to a operate, why there aren’t any arrays of references and why studying the fallacious member of a union is a bug.

This information covers every sort of compound kind with a brief, full program: arrays, pointers and references, courses, unions and std::variant, enumerations, capabilities and tips that could members. It then exhibits how compound sorts mix into declarations resembling int (*)[3], and find out how to learn them. Each program was compiled and examined with GCC and Clang (C++17 and C++20, warnings as errors) and with MSVC on Home windows 11, and each output under is captured verbatim.

The Quick Reply

What are compound sorts in C++? Sorts constructed from different sorts. The usual lists eight sorts: arrays, capabilities, pointers, references, courses (together with structs), unions, enumerations and tips that could members.

What are the elemental sorts? The categories constructed into the language: void, std::nullptr_t, bool, the character sorts, the integer sorts and the floating-point sorts. Each different kind is compound.

Is std::string a compound kind? Sure. It’s a class, and each class is a compound kind, whether or not the language or the usual library defines it.

What Is a Compound Sort in C++?

A compound kind in C++ is any kind that isn’t a basic kind. Compound sorts are constructed from different sorts: an array of int, a pointer to double, a reference to a std::string, a category with members of a number of sorts, or a operate kind constructed from its parameter and return sorts. The usual library reviews the class by way of std::is_compound.

The C++ customary divides each kind into two teams. The elemental sorts are inbuilt. The compound sorts are constructed from them, and from one another. cppreference’s web page on sorts lists the total classification, with the sort trait that assessments every class.

Type of compound kind Instance Constructed from
Array int[4] A component kind and a size
Perform int(int, int) Parameter sorts and a return kind
Pointer int* The kind it factors to
Reference int&, int&& The kind it refers to
Class (together with struct) Level, std::string Its members’ sorts
Union Quantity Its members’ sorts, sharing one block of reminiscence
Enumeration enum class Coloration An underlying integer kind
Pointer to member int Level::* A category and one in all its members’ sorts
C++ sorts: basic and compound Each kind is one or the opposite. The classes under are those type_census.cpp reviews. Basic constructed into the language void std::nullptr_t bool characters char, wchar_t, char16_t, char32_t integers quick, int, lengthy, lengthy lengthy, unsigned floating level float, double, lengthy double is_compound_v<T>: false Arrays int[4] N components of 1 kind Capabilities int(int, int) parameter and return sorts Pointers int* tackle of an object or operate References int& int&& one other title for an object Lessons struct Level, std::string members of any sorts Unions union Quantity members share the identical bytes Enumerations enum class Coloration named integer constants Tips to members int Level::* a member of a category Compound sorts are constructed from different sorts, and so they mix: int* [3] array of three pointers int (*)[3] pointer to an array of three int (*)(double) pointer to a operate taking double, returning int
Determine 1: Each C++ kind is prime or compound. The eight compound sorts on the fitting are constructed from different sorts and will be mixed, because the declarations on the backside present.

You would not have to memorize the desk. The kind traits in <type_traits> reply the identical questions at compile time, and this program asks them about one kind of every type:

// type_census.cpp - asks the compiler which class every kind belongs to.
// The kind traits in <type_traits> reply the identical questions the C++
// customary makes use of to divide sorts into basic and compound.
#embody <cstddef>
#embody <iomanip>
#embody <iostream>
#embody <string>
#embody <type_traits>

struct Level { int x; int y; };

class Account {
public:
    double steadiness() const { return balance_; }
personal:
    double balance_ = 0;
};

union Quantity { int i; float f; };

enum class Coloration { crimson, inexperienced, blue };

template <typename T>
const char* class()
{
    if constexpr (std::is_fundamental_v<T>) return "basic";
    else if constexpr (std::is_array_v<T>) return "array";
    else if constexpr (std::is_function_v<T>) return "operate";
    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 knowledge member";
    else if constexpr (std::is_member_function_pointer_v<T>) return "pointer to member operate";
    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* title)
{
    std::cout << std::left << std::setw(30) << title
              << std::setw(13) << (std::is_compound_v<T> ? "compound" : "basic")
              << class<T>() << 'n';
}

int primary()
{
    std::cout << std::left << std::setw(30) << "kind" << std::setw(13) << "type" << "categoryn";
    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<Level>("Level (struct)");
    row<Account>("Account (class)");
    row<Quantity>("Quantity (union)");
    row<Coloration>("Coloration (enum class)");
    row<int Level::*>("int Level::*");
    row<double (Account::*)() const>("double (Account::*)() const");
    row<std::string>("std::string");
}

Output:

kind                          type         class
int                           basic  basic
double                        basic  basic
bool                          basic  basic
void                          basic  basic
std::nullptr_t                basic  basic
int[4]                        compound     array
int(int, int)                 compound     operate
int*                          compound     pointer
int&                          compound     lvalue reference
int&&                         compound     rvalue reference
Level (struct)                compound     class
Account (class)               compound     class
Quantity (union)                compound     union
Coloration (enum class)            compound     enumeration
int Level::*                  compound     pointer to knowledge member
double (Account::*)() const   compound     pointer to member operate
std::string                   compound     class

Three outcomes are price noticing:

  • void and std::nullptr_t are basic, despite the fact that neither holds a quantity.
  • A struct is a category. Level and Account land in the identical class; the one distinction between struct and class is the default entry of members and base courses.
  • Library sorts are compound too. std::string is reported precisely like Level, as a result of to the language it’s simply one other class.

Arrays: A Sort That Consists of Its Size

An array kind has two components: the ingredient kind and the variety of components. double[4] and double[5] are differing kinds. That size is straightforward to lose, as a result of an array converts to a pointer to its first ingredient virtually in every single place it’s used, together with when it’s handed to a operate:

// arrays.cpp - an array's kind contains its size. The size is misplaced when
// the array decays to a pointer, and saved by a reference to the array or by
// std::array.
#embody <array>
#embody <cstddef>
#embody <iomanip>
#embody <iostream>
#embody <iterator>
#embody <type_traits>

// Receives solely an tackle, so the caller should move the depend individually.
double total_by_pointer(const double* costs, std::size_t depend)
{
    double sum = 0;
    for (std::size_t i = 0; i < depend; ++i)
        sum += costs[i];
    return sum;
}

// A reference to an array retains the size within the kind: N is deduced.
template <std::size_t N>
double total_by_reference(const double (&costs)[N])
{
    double sum = 0;
    for (double p : costs)
        sum += p;
    return sum;
}

// std::array is a category wrapping a C array: it may be handed, copied and
// returned like another worth, and it all the time is aware of its measurement.
double total_of(const std::array<double, 4>& basket)
{
    double sum = 0;
    for (double p : basket)
        sum += p;
    return sum;
}

int primary()
{
    std::cout << std::fastened << std::setprecision(2);

    double costs[] = {19.99, 5.49, 3.75, 12.00};
    static_assert(std::is_same_v<decltype(costs), double[4]>, "the size is a part of the sort");
    std::cout << "sizeof(costs) = " << sizeof(costs) << " bytes, "
              << std::measurement(costs) << " elementsn";

    const double* first = costs;   // the array decays to a pointer to its first ingredient
    std::cout << "sizeof(first) = " << sizeof(first) << " bytes: solely the tackle is leftn";

    std::cout << "complete by pointer and depend:  " << total_by_pointer(costs, std::measurement(costs)) << 'n';
    std::cout << "complete by reference to array: " << total_by_reference(costs) << 'n';

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

Output:

sizeof(costs) = 32 bytes, 4 components
sizeof(first) = 8 bytes: solely the tackle is left
complete by pointer and depend:  41.23
complete by reference to array: 41.23
std::array: measurement() = 4, complete = 41.23, copy complete = 21.24

The primary two traces present the conversion. sizeof(costs) is 32 bytes, 4 doubles, however after const double* first = costs; solely an 8-byte tackle is left. The sizes are from a 64-bit construct; a 32-bit construct prints 4 for the pointer. A operate that receives the pointer can’t get well the size, which is why total_by_pointer wants a separate depend parameter, and why passing the fallacious depend is a traditional out-of-bounds bug.

There are two methods to maintain the size:

  • A reference to an array retains the entire kind, const double (&)[4]. The template parameter N is deduced from it, so total_by_reference(costs) wants no depend.
  • std::array<double, 4> is a category that wraps an array. It may be copied with = (a plain array can’t) and returned from a operate, and it all the time is aware of its measurement(). Modifying copy[0] left basket unchanged, as the 2 totals present.

For brand new code, choose std::array for a hard and fast measurement and std::vector for a variable one. Arrays in C and C++ covers the reminiscence format and multidimensional arrays in additional depth.

Pointers and References

A pointer is an object that shops an tackle. It may be null, and it may be modified to level to one thing else. A reference is one other title for an current object. It should be sure when it’s created and by no means modifications what it refers to:

// pointers_references.cpp - a pointer is an object holding an tackle; it could possibly
// be null and will be pointed some place else. A reference is one other title for
// an current object; it should be sure when created and by no means modifications goal.
#embody <iostream>

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

void add_bonus(int& rating)          // the caller passes an object; no null examine wanted
{
    rating += 10;
}

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

    int* p = &alice;
    *p += 1;                         // modifications alice by way of the pointer
    p = &bob;                        // the pointer now factors to bob
    *p += 1;
    std::cout << "after pointer:   alice = " << alice << ", bob = " << bob << 'n';

    int& r = alice;                  // r is one other title for alice, for good
    r = bob;                         // copies bob's worth into alice; r nonetheless names alice
    r += 1;
    std::cout << "after reference: alice = " << alice << ", bob = " << bob << 'n';

    add_bonus(&bob);
    add_bonus(nullptr);              // allowed, and the operate should examine
    add_bonus(alice);
    std::cout << "after bonuses:   alice = " << alice << ", bob = " << bob << 'n';

    const int* read_only = &alice;   // pointer to const: can't change alice by way of it
    int* const fastened = &bob;         // const pointer: can't level elsewhere
    *fastened += 5;                     // allowed: the int it factors to isn't const
    std::cout << "read_only -> " << *read_only;
    read_only = &bob;                // allowed: the pointer itself isn't const
    std::cout << ", re-pointed -> " << *read_only << ", fastened -> " << *fastened << '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, fastened -> 86

The second line is the one which surprises individuals. r = bob; doesn’t make r seek advice from bob. It assigns bob‘s worth (71) to alice, as a result of r is alice, after which r += 1 makes alice 72. There is no such thing as a syntax for re-pointing a reference.

That distinction decides which one a operate ought to take. add_bonus(int*) accepts nullptr, so it has to examine. add_bonus(int&) can’t obtain a null reference, so it wants no examine. A very good default is to make use of a reference when an object is required, and a pointer when “no object” is a sound enter.

The final line exhibits the 2 locations const can go. const int* protects the int: read_only can’t change alice, however it may be pointed at bob. int* const protects the pointer: fastened can change bob however can’t level wherever else. Learn the declaration from proper to left: “fastened is a const pointer to int“.

As a result of a reference isn’t an object, two declarations that look cheap don’t compile. The repository’s assessments construct each and examine that the compiler rejects them:

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

To retailer references in an array or a container, use pointers or std::reference_wrapper. Pointers, pointer arithmetic and const-correctness are lined in additional depth in pointers in C++, and proudly owning pointers in good pointers in fashionable C++.

Lessons and Structs

A category is essentially the most versatile compound kind: its members will be of any sorts, together with different compound sorts, and it provides member capabilities, entry management, constructors and destructors. struct and class declare the identical sort of kind. The one variations are the defaults:

Characteristic struct class
Default member entry public personal
Default base-class entry public personal
Can have member capabilities, constructors, base courses Sure Sure
What std::is_class_v reviews true true

By conference, struct is used for easy teams of public knowledge, like Level, and class for sorts that defend their knowledge behind member capabilities, like Account. The Worker struct within the pointers-to-members part under is a typical struct. How courses are designed, from constructors to static members, is the topic of courses in object-oriented programming.

Unions, Tagged Unions and std::variant

A union is a category whose members all begin on the similar tackle, so it’s only as massive as its largest member, and just one member holds a worth at a time. The union doesn’t file which one. Writing one member after which studying one other is undefined conduct in C++, though C permits it, a distinction that catches code shifting between the 2 languages (union in C covers the C guidelines). To have a look at the bytes of a float, copy them with std::memcpy (or use C++20’s std::bit_cast) as an alternative:

// unions_variant.cpp - a union shops one in all a number of members in the identical
// bytes and doesn't file which one. A tagged union provides that file by
// hand; std::variant does it routinely and checks each entry.
#embody <cstdint>
#embody <cstring>
#embody <iomanip>
#embody <iostream>
#embody <string>
#embody <type_traits>
#embody <variant>
#embody <vector>

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

// A tagged union: the enum says which member of the union is lively.
struct Setting {
    enum class Sort { integer, actual } type;
    union {
        int i;
        double d;
    } worth;
};

void print(const Setting& s)
{
    change (s.type) {
    case Setting::Sort::integer: std::cout << "integer " << s.worth.i << 'n'; break;
    case Setting::Sort::actual:    std::cout << "actual " << s.worth.d << 'n'; break;
    }
}

// The identical concept with std::variant: the sort remembers which different it holds.
utilizing Worth = 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 primary()
{
    std::cout << "sizeof(Quantity) = " << sizeof(Quantity) << " (members share the identical 4 bytes)n";

    Quantity n;
    n.f = 1.0f;     // f is now the lively member; studying n.i'd be undefined conduct

    // To see a float's bits, copy them into an integer as an alternative of studying the
    // inactive member. (C++20 provides std::bit_cast for a similar 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::Sort::integer, {}};
    timeout.worth.i = 30;
    Setting ratio{Setting::Sort::actual, {}};
    ratio.worth.d = 0.75;
    print(timeout);
    print(ratio);

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

    Worth v = 2.5;
    std::cout << "holds double? " << std::boolalpha << std::holds_alternative<double>(v) << 'n';
    attempt {
        std::cout << std::get<int>(v) << 'n';      // fallacious different
    } catch (const std::bad_variant_access&) {
        std::cout << "std::get<int> on a double: std::bad_variant_accessn";
    }
}

Output:

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

This system exhibits three ranges of security:

  • A plain union (Quantity) is 4 bytes for an int and a float, and nothing stops you from studying the fallacious member. 0x3f800000 is the IEEE 754 bit sample of 1.0, obtained with memcpy, which is properly outlined.
  • A tagged union (Setting) shops an enum subsequent to the union to file which member is lively, and each reader should examine it. That is the traditional sample in C and in older C++ code.
  • std::variant (C++17) is a tagged union managed by the library. It data the lively different, and std::go to calls the fitting overload of Describe. Asking for the fallacious kind with std::get<int> throws std::bad_variant_access as an alternative of returning rubbish.

Use std::variant in new C++ code, and maintain uncooked unions for memory-mapped {hardware}, binary codecs and interfaces with C. cppreference’s std::variant reference lists the total interface.

Enumerations

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

  • Plain enum, inherited from C: its names are seen within the surrounding scope and convert to int routinely.
  • enum class (C++11): its names are scoped (Coloration::crimson) and by no means convert to int with no static_cast. Its underlying kind will be chosen, as in enum class Coloration : std::uint8_t.

Coloration within the kind census is an enum class, and std::is_enum_v reviews it as an enumeration, not as an integer. Desire enum class in C++. Enum in C covers enums in depth, together with a piece on how C++ enum class differs from C’s enums.

Tips to Members

A pointer to member names a member of a category, not a member of 1 object. &Worker::age means “the age member of any Worker“. Utilized to an object with .* (or ->* by way of a pointer), it selects that member of that object. This lets one operate work on whichever area it’s given:

// member_pointers.cpp - a pointer to member names a member of a category, not a
// member of 1 object. Utilized to an object with .* or ->*, it selects that
// member. Right here one type operate types by whichever area it's given.
#embody <algorithm>
#embody <useful>
#embody <iomanip>
#embody <iostream>
#embody <string>
#embody <vector>

struct Worker {
    std::string title;
    int age;
    double wage;

    double month-to-month() const { return wage / 12; }
};

template <typename T>
void sort_by(std::vector<Worker>& employees, T Worker::*area)
{
    std::type(employees.start(), employees.finish(),
              [field](const Worker& a, const Worker& b) { return a.*area < b.*area; });
}

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

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

    sort_by(employees, &Worker::title);
    print("by title  ", employees);
    sort_by(employees, &Worker::age);
    print("by age   ", employees);
    sort_by(employees, &Worker::wage);
    print("by wage", employees);

    int Worker::*area = &Worker::age;          // pointer to knowledge member
    double (Worker::*pay)() const = &Worker::month-to-month;   // pointer to member operate

    const Worker& first = employees.entrance();
    std::cout << std::fastened << std::setprecision(2);
    std::cout << first.title << ": age " << first.*area << ", month-to-month " << (first.*pay)()
              << ", by way of std::invoke " << std::invoke(pay, first) << 'n';
}

Output:

by title  : Lena Maya Omar Ravi
by age   : Omar Lena Maya Ravi
by wage: Ravi Omar Maya Lena
Ravi: age 52, month-to-month 6333.33, by way of std::invoke 6333.33

sort_by is written as soon as and types by a std::string, an int or a double, as a result of T Worker::*area deduces the member’s kind. The identical concept works for member capabilities: double (Worker::*)() const factors to month-to-month, and (first.*pay)() calls it. The parentheses are required, as a result of () binds extra tightly than .*. std::invoke(pay, first) calls it with out the awkward syntax, and it’s how the usual library itself calls member pointers. Tips to members are rarer than the opposite compound sorts, however they seem in sorting and projection code, in serialization libraries and in signal-and-slot frameworks.

Combining Compound Sorts: Studying Declarations

Compound sorts are constructed from different sorts, together with different compound sorts. That’s the place C++ declarations get laborious to learn. The rule that works: begin on the title, learn proper (arrays and performance parameters), then left (pointers and references), and let parentheses change the order.

// declarations.cpp - compound sorts mix. Learn a declaration from the title
// outward: proper first (arrays, operate parameters), then left (pointers,
// references), and parentheses change the order.
#embody <cstddef>
#embody <iostream>
#embody <type_traits>

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

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

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

    int* pointers[3] = {&a, &b, &c};   // array of three tips that could int
    int (*to_row)[3] = &row;           // pointer to an array of three int
    int (*fn)(double) = &twice;        // pointer to a operate taking double, returning int
    int& (*counter_fn)() = &next_counter;   // pointer to a operate 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 decision returns a reference, so it may be assigned
    std::cout << "counter = " << counter << 'n';

    // Sort aliases make the identical sorts readable.
    utilizing Row = int[3];
    utilizing Rework = int (*)(double);
    Row* same_as_to_row = &row;
    Rework same_as_fn = twice;       // a operate title decays to a pointer, like an array
    static_assert(std::is_same_v<Row*, decltype(to_row)>);
    std::cout << "by way of 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
by way of aliases: 9, 2

Making use of the rule:

  • int* pointers[3]: pointers is an array of three (proper), of tips that could int (left). It’s 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 three int (proper). It’s one 8-byte pointer.
  • int (*fn)(double): fn is a pointer to a operate taking a double and returning int.
  • int& (*counter_fn)(): a pointer to a operate returning int&. As a result of the decision returns a reference, counter_fn() += 100 modifications counter itself, which ends at 101.

The static_assert traces are the compiler confirming every studying; if one had been fallacious, this system wouldn’t construct. Capabilities are compound sorts too, which is why fn has a operate kind inside its pointer kind. A operate title converts to a pointer to the operate, simply as an array title converts to a pointer to its first ingredient, which is why Rework same_as_fn = twice; wants no &. How capabilities themselves are declared and referred to as is roofed in capabilities in C++.

In actual code, title the components. utilizing Row = int[3]; and utilizing Rework = int (*)(double); flip the toughest declarations into Row* and Rework, and std::operate<int(double)> is usually clearer nonetheless for callbacks.

Frequent Errors with Compound Sorts

  • Utilizing sizeof on an array parameter. A parameter written double costs[] is a pointer, so sizeof(costs) contained in the operate provides the pointer’s measurement. GCC and Clang each warn about this by default (-Wsizeof-array-argument). Cross a reference to the array, a std::array, or a std::span (C++20) as an alternative.
  • Studying the inactive member of a union. It compiles and sometimes seems to work, however it’s undefined conduct in C++. The repository’s pitfalls/inactive_member.cpp does precisely this: it builds with no warning below -Wall -Wextra -pedantic, and AddressSanitizer and UndefinedBehaviorSanitizer keep silent when it runs, so no software will catch it for you. Use std::variant, or memcpy to reinterpret bytes.
  • Anticipating r = different; to rebind a reference. It assigns by way of the reference. If the goal should change, use a pointer.
  • Returning a pointer or reference to a neighborhood variable. The native is destroyed when the operate returns, and the pointer or reference dangles. GCC (-Wreturn-local-addr) and Clang (-Wreturn-stack-address) warn in regards to the direct case by default. When the reference goes by way of a neighborhood variable first (int& r = x; return r;), Clang nonetheless warns, however GCC 13 warns solely in an optimized construct (-O2), so deal with the warnings as a security internet, not a assure.
  • Forgetting the parentheses in a declaration. int* p[3] and int (*p)[3] are differing kinds. When doubtful, use a utilizing alias.

Key Takeaways

  • Each C++ kind is prime or compound. Basic sorts are inbuilt; compound sorts are constructed from different sorts, and std::is_compound_v tells them aside.
  • There are eight sorts of compound kind: arrays, capabilities, pointers, references, courses, unions, enumerations and tips that could members.
  • An array’s size is a part of its kind, and it’s misplaced when the array decays to a pointer. Use a reference to the array, std::array or std::span to maintain it.
  • A reference is one other title for an object. It should be initialized, can’t be null and can’t be re-pointed, so there aren’t any arrays of references.
  • A union doesn’t know which member it holds. std::variant does, and it checks each entry.
  • Compound sorts mix. Learn declarations from the title outward, proper then left, and use utilizing aliases to maintain them readable.

Conclusion

Compound sorts are how C++ builds every thing past a single quantity: an array is a kind plus a depend, a pointer is a kind plus an tackle, a category is a set of sorts below one title. A lot of the language’s sharp edges, from array decay to dangling references to unions with no tag, come from the foundations of 1 explicit compound kind, and understanding which sort you’re holding is the quickest technique to predict the way it behaves.

For extra C++ fundamentals and the remainder of the language, see the C++ part.

Supply Code and Exams

compound-types workflow status

All packages on this web page are within the fundamentals/compound-types listing of the MYCPLUS C++ examples repository.

Construct and take a look at:

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

What the construct checks.

  • Compilers: GCC and Clang below C++17 and C++20 with -Wall -Wextra -pedantic -Werror, and MSVC with /W4 /WX /permissive-.
  • Output: every of the six packages prints precisely the output proven on this web page.
  • Compile failures: the array of references and the unbound reference should fail to construct, with a compiler message that names the issue. A construct that fails for another purpose doesn’t depend as a move.
  • Sanitizers: on Linux, each take a look at additionally runs below AddressSanitizer and UndefinedBehaviorSanitizer.

What I Verified

All the pieces within the Ubuntu column was run for this text on Ubuntu 24.04 (x86-64, GCC 13.3, Clang 18.1, CMake 3.28). The Home windows column comes from run_all.ps1 within the repository, run on Home windows 11 (construct 26300) with MSVC.

Examine Ubuntu 24.04 Home windows 11
Construct with warnings as errors GCC and Clang, C++17 and C++20: handed MSVC /W4 /WX /permissive-, C++17 and C++20: handed
CTest: 6 output comparisons and a couple of packages that should not compile 8 of 8 in all 4 configurations 8 of 8 in C++17 and in C++20
AddressSanitizer and UndefinedBehaviorSanitizer, each take a look at 8 of 8, clear Not relevant
Valgrind memcheck, each program No errors, no leaks Not relevant
Deliberate errors: a compile-fail program that compiles, one which fails for an unrelated purpose, a modified anticipated output All three caught Not run

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

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments