Skip to content

Structs and Classes

Derek Snider edited this page May 19, 2026 · 1 revision

Structs & Classes

Structs

struct Point {
    int x;
    int y;
};

int main() {
    Point p;
    p.x = 10;
    p.y = 20;
    cout << p.x << ", " << p.y << endl;
    return 0;
}

No struct prefix needed when declaring variables — Point p; works directly.

Brace initialization

Point p = { 10, 20 };

Pointers and -> access

Point p = { 10, 20 };
Point *ptr = &p;
cout << ptr->x << endl;     // 10

Chained access works: a->b->c, a->b.c, a.b.c.

Alignment and packing

Structs use natural x86-64 C ABI alignment by default — they can be passed directly to C library functions like stat() or localtime().

__attribute__((packed))

struct __attribute__((packed)) header {
    char magic;     // offset 0
    int32_t size;   // offset 1 (no padding)
    int64_t data;   // offset 5 (no padding)
};
// total size: 13 bytes

#pragma pack

#pragma pack(push, 1)
struct packed { char x; int y; };   // 5 bytes
#pragma pack(pop)                   // back to default

sizeof

sizeof(int)              // 8 (madc int is 64-bit)
sizeof(int32_t)          // 4
sizeof(struct Point)     // depends on fields

sizeof resolves at parse time to an integer constant.

Classes with methods

class Counter {
    int count;

    void inc() {
        count = count + 1;
    }

    int get() {
        return count;
    }
};

int main() {
    Counter c;
    c.count = 0;
    c.inc();
    c.inc();
    c.inc();
    cout << c.get() << endl;   // 3
    return 0;
}

Methods access instance data through a hidden this pointer. Each instance operates on its own data:

Counter a;
Counter b;
a.count = 0;
b.count = 100;
a.inc();        // a.count = 1
b.inc();        // b.count = 101

String members

Struct and class members can be strings:

struct Person {
    string name;
    int age;
};

Person bob;
bob.name = "Bob Smith";
bob.age = 42;
cout << bob.name << ", age " << bob.age << endl;

String members are automatically constructed and destructed when the struct goes in and out of scope.

What's next?

Clone this wiki locally