Lesson 13 of 25

Structures

Defining Structs

Structures (structs) group related variables under one name. In C++, structs can also have methods, making them similar to classes.

Example
struct Point {
    double x;
    double y;

    // Method
    double distanceTo(const Point& other) const {
        double dx = x - other.x;
        double dy = y - other.y;
        return sqrt(dx * dx + dy * dy);
    }
};

// Create and use struct
Point p1 = {3.0, 4.0};
Point p2 = {0.0, 0.0};
cout << p1.distanceTo(p2) << endl; // 5.0

// Struct with default values
struct Config {
    int width = 800;
    int height = 600;
    bool fullscreen = false;
    string title = "My App";
};

Config cfg;  // uses defaults
Config custom = {1920, 1080, true, "Game"};