Structs: Your Own Data Types

Keeping things together

A student has a name, an age and a grade. You could keep three separate variables, but they belong together. A struct lets you create your own type that bundles them up:

#include <iostream>
#include <string>
using namespace std;

struct Student {
    string name;
    int age;
    double grade;
};

int main() {
    Student s;
    s.name = "Priya";
    s.age = 19;
    s.grade = 8.7;
    cout << s.name << " is " << s.age << " and has grade " << s.grade << "\n";
    return 0;
}

Output

Priya is 19 and has grade 8.7
  • struct Student { ... }; describes the new type. Note the semicolon after the }!
  • The variables inside are called members (or fields).
  • Use a dot to reach a member: s.name, s.age.

Think of it like this: A struct is like a form with boxes: Name ___, Age ___, Grade ___. The struct is the blank form; each variable of that type is one filled-in copy.

Creating a struct in one line

#include <iostream>
#include <string>
using namespace std;

struct Point {
    int x;
    int y;
};

int main() {
    Point a = {3, 4};
    Point b = {10, -2};
    cout << "a = (" << a.x << ", " << a.y << ")\n";
    b.x += 5;
    cout << "b = (" << b.x << ", " << b.y << ")\n";
    return 0;
}

Output

a = (3, 4)
b = (15, -2)

Default values for members

#include <iostream>
#include <string>
using namespace std;

struct Settings {
    int volume = 50;
    bool darkMode = false;
    string language = "English";
};

int main() {
    Settings mine;
    mine.darkMode = true;
    cout << mine.volume << " " << mine.darkMode << " " << mine.language << "\n";
    return 0;
}

Output

50 1 English

Common mistake: Forgetting the semicolon after the closing brace of a struct: struct Point { int x; int y; };

HOME LABS COMMUNITY DASHBOARD