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).

Creating a struct#

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.

Initializing a struct#

There are several ways we can initialize our struct. Once we create a Planet, we can initialize the components separately, or we can use a list-initialization.

Listing 38 struct_init.cpp#
#include <iostream>
#include <format>
#include <string>

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

int main() {

    // create empty Planet and initialize later
    Planet p1{};
    p1.name = "Mercury";
    p1.a = 0.3871;
    p1.e = 0.2056;

    // use initialization list
    Planet p2{"Venus", 0.7233, 0.0068};

    // specify components in initialization list
    Planet p3{.name="Earth", .a=1.0000, .e=0.0167};

    std::cout << std::format("Planet {} has a = {} AU and e = {}\n",
                             p1.name, p1.a, p1.e);

    std::cout << std::format("Planet {} has a = {} AU and e = {}\n",
                             p2.name, p2.a, p2.e);

    std::cout << std::format("Planet {} has a = {} AU and e = {}\n",
                             p3.name, p3.a, p3.e);

}

Note

We define the struct Planet outside of the main function.