Structures

It is often handy to group related data together into a user-defined data structure. A simple way to do this in C++ is with a structure.

Table of Contents

  1. Why Structures
  2. Defining Structures
  3. Using Structures and their Members
  4. Structures and Collections
  5. Structs and Class
  6. Further Reading

Why Structures

We normally reach for a structure when we notice that we are passing around the same set of data in many places within our program.

For example, we might notice that we are often passing around the x and y coordinate for a point in a 2D drawing program.

void drawLine(int x1, int y1, int x2, int y2);
void drawTriangle(int x1, int y2, int x2, int y2, int x3, int y3);

It might be nice here to have a structure that represents a point with an x and y value.

void drawLine(Point p1, Point p2);
void drawTriangle(Point p1, Point p2, Point p3);

We can now also return Points from a function, something we couldn’t do when we were working with separate x and y values.

Point generateRandomPoint();

Defining Structures

Structures are defined using the struct keyword:

struct Point {
  int x;
  int y;
};

⚡ Warning:

Don’t forget the semicolon after the close curly brace.

Using Structures and their Members

Let’s define a variable using the point struct defined above. Notice that we can initialize the structure’s members using an initializer list, and that the members can be publicly accessed and modified.

#include <iostream>
#include <vector>

struct Point {
  int x;
  int y;
};

int main() {
  Point point{ 5, 10 }; // Initializer list: x = 5 and y = 10

  // Public get access to members:
  std::cout << "x: " << point.x << " y: " << point.y << "\n";

  // Public set access to members:
  point.x++;
  point.y = point.x * 10;

  std::cout << "x: " << point.x << " y: " << point.y << "\n";

  std::vector<Point> polygon;

  std::vector<Point> square{ {0, 0}, {0, 12}, {12, 12}, {12, 0} };

  std::cout << square[2].x << "\n";
}

🎵 Note:

Initializer lists provide values for struct members in the order in which they are defined.

Structures and Collections

Once a structure has been defined you can use it like any other type with collections like arrays and vectors.

  std::vector<Point> polygon{ {0, 0}, {1, 12}, {12, 10}, {12, 5} };

  std::cout << "x: " << polygon[2].x  << " y: " << polygon[2].y << "\n"

Structs and Class

We can add constructors, destructors, and other methods to structs, at which point they start to look a lot like classes.

The truth is that there is little difference between a struct and a class. The difference is that if you don’t specify the visibility of members (public, private, protected) they will default to public in a struct and default to private in a class.

💡 Best Practice:

Use struct for data-only structures and class for objects with data and behaviours.

Further Reading