Creating your own data types with structs in C++

I’ve known about structs for many years through libraries, yet it has never occurred to me to create my own. They can really come in handy, and before I forget how they work, I thought I’d make a note about them. Structs in C are data types that can hold values, and they’re great to keep properties of related data together.

Say I had an object on which I’d like to track a size and a value. Here’s how I can create it as a struct. This happens outside a method or function declaration.

// create a struct

struct Awesomeness {
    int heigth;
    int width;
    float value;
};

Inside my method, I can now create a new instance of these and give them values.

// initialise my struct

    Awesomeness myAwesome;
    myAwesome.heigth = 640;
    myAwesome.width = 480;
    myAwesome.value = 3.141592654;

    float result = myAwesome.value * 10;

We can access values inside out structs with dot notation, so myAwesome.value will refer to the struct member variable of value.

Initialisation can also be done with braces and on a single line by passing in the arguments in the expected order, like this:

// braced initialisation

Awesomeness myAwesome {640, 480, 3.1415};

Structs within structs

We can also add an existing struct to our own struct. Let’s take the Rectangle struct from the raylib library as an example. I’ll create a struct with a float and a Rectangle struct, then initialise it.

// declare my struct
struct DoubleStruct {
    int myValue;
    Rectangle myRect;
};

// initialise it
DoubleStruct myStruct {4.2, 640, 480, 0, 0};

// access values
float result = myStruct.myRect.width * 2;

To access a value in the second struct, we’ll use double-dot notation. I wonder how many levels deep this can be done before a serious error is thrown…? Let’s worry about that another day!

You can leave a comment on my original post.