-
Notifications
You must be signed in to change notification settings - Fork 0
Structs and Classes
Derek Snider edited this page May 19, 2026
·
1 revision
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.
Point p = { 10, 20 };Point p = { 10, 20 };
Point *ptr = &p;
cout << ptr->x << endl; // 10Chained access works: a->b->c, a->b.c, a.b.c.
Structs use natural x86-64 C ABI alignment by default — they can be passed directly to C library functions like stat() or localtime().
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(push, 1)
struct packed { char x; int y; }; // 5 bytes
#pragma pack(pop) // back to defaultsizeof(int) // 8 (madc int is 64-bit)
sizeof(int32_t) // 4
sizeof(struct Point) // depends on fieldssizeof resolves at parse time to an integer constant.
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 = 101Struct 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.
- Pointers & Arrays — C-style pointers, fixed arrays, subscripts
- Functions — class methods, function pointers, lambdas
- Data Types — all types including containers
- ← Back to Home