Class layout & this
Members laid out like a struct; methods take a hidden `this` pointer.
Before you start
A **class** looks like a big new idea — data and functions bundled together — but in memory it is almost boring. The data members sit next to each other exactly like a C struct. The methods don't sit inside the object at all; they live in the program's code section, shared by every instance.
So how does a.speak() know which object's data to use? The compiler passes a hidden extra argument called this — a pointer to the object you called the method on. Inside the method, name really means this->name.
This lesson shows a class object in memory (just the fields, nothing more), and demonstrates how the same shared method finds different data for different objects via this.
Stack
objects laid out like structsTwo ints, 4 bytes each = 8 bytes total. No method table, no overhead.
Step 1 of 6. A class is a struct with access control. `Point` has two `int` members: `x` and `y`. In memory, the object is 8 bytes — exactly like a C struct with two ints. No methods are stored inside it. `class` and `struct` produce the same layout. The only difference is that `class` members default to private and `struct` members default to public.
Step 01 / 06
A class is a struct with access control
Point has two int members: x and y. In memory, the object is 8 bytes — exactly like a C struct with two ints. No methods are stored inside it.
class and struct produce the same layout. The only difference is that class members default to private and struct members default to public.
class Point { int x; int y;public: Point(int x, int y) : x(x), y(y) {} double length() const { return sqrt(x*x + y*y); } void set(int nx, int ny) { this->x = nx; this->y = ny; }};// sizeof(Point) == 8: two ints, no hidden fieldsPoint a(3, 4);Point b(1, 2);a.length(); // compiler passes &a as 'this'b.length(); // compiler passes &b as 'this'