Structures

Structures#

A structure (or struct) is a compound datatype that can hold a mix of data. In C++, a struct shares many similarities to a class—both hold data as well as functions that work on the data (called members).

Consider the following:

struct Planet
{
    std::string name{};
    double a{};            // semi-major axis
    double e{};            // eccentricity
};

This is a structure that can describe some basic properties of a planet, including its name, semi-major axis, and eccentricity of the orbit.

Tip

A common mistake is to forget the ; after the definition of the struct.

We can create a Planet object via:

Planet p;

Then we can access the different members of the struct using the “.” operator, e.g. p.name, p.a, and p.e.

Let’s look at a program that stores the basic properties for the planets in our solar system and then loops over them and computes their orbital period using Kepler’s third law:

\[\left ( \frac{P}{\mathrm{year}} \right )^2 = \left ( \frac{a}{\mathrm{AU}} \right )^3\]
Listing 40 struct_example.cpp#
#include <iostream>
#include <vector>
#include <cmath>
#include <format>

struct Planet
{
    std::string name{};
    double a{};            // semi-major axis
    double e{};            // eccentricity
};

int main() {

    const std::vector<Planet> planets{{.name="Mercury", .a=0.3871, .e=0.2056},
                                      {.name="Venus",   .a=0.7233, .e=0.0068},
                                      {.name="Earth",   .a=1.0000, .e=0.0167},
                                      {.name="Mars",    .a=1.5237, .e=0.0934},
                                      {.name="Jupiter", .a=5.2029, .e=0.0484},
                                      {.name="Saturn",  .a=9.5370, .e=0.0539},
                                      {.name="Uranus",  .a=19.189, .e=0.0473},
                                      {.name="Neptune", .a=30.070, .e=0.0086}};

    for (const auto& p : planets) {
        std::cout << std::format("{} has a period of {:.2f} years\n",
                                 p.name, std::sqrt(std::pow(p.a, 3)));
    }

}

Some notes:

  • We put the definition of Planet outside of the main() function.

  • In the initialization of the planets vector, we use list-initialization for each of the planets in its own set of {}.

  • Notice that our vector planets is const. This means that we cannot add to it (e.g., via .push_back()).

Note

As mentioned above, a class is very similar to a struct in C++. The main difference is that in a struct all of the members are publicly accessible while in a class, they are private unless we make them public.

Note

A common consideration when organizing data that is associated together is whether to do a struct-of-arrays or an array-of-structs. See this discussion on AoS and SoA.

In our planet example above, we created an array of structs. This is a natural organization if we want to loop over planets and access their data individually.