Class Basics
Classes are where C++ object orientation lives. Data and the functions that act on it, packaged together.
Defining a Class
class Rectangle {private: double width; double height;
public: Rectangle(double w, double h) : width(w), height(h) {}
double area() const { return width * height; } double perimeter() const { return 2 * (width + height); }
void scale(double factor) { width *= factor; height *= factor; }};In memory a Rectangle is just its two doubles. The member functions aren't in the object at all: they're ordinary functions in the program's code, and each call passes the object's address as a hidden first argument, this (in rdi on x86-64 Linux). The this pointer section below unpacks that.
sizeof(Rectangle) on x86-64
| Offset | Field | Size | Notes |
|---|---|---|---|
| 0x0 (0) | double width | 8 | this + 0 |
| 0x8 (8) | double height | 8 | this + 8. area(), perimeter() and scale() take no space here. |
sizeof = 16 bytes, 0 of them padding; alignment 8.
Access Specifiers
private- only accessible inside the class (default forclass)public- accessible from anywhereprotected- accessible inside the class and its subclasses
Encapsulation hides the messy bits behind a public interface. Whoever calls Rectangle::area() neither knows nor cares whether you store width/height or diagonal/angle inside. Swap the internals later and the call sites don't budge.
Encapsulation earns its keep when a class has a rule to protect. This account must never go negative, and because balance is private, the methods are the only way in. Run it and look hard at the second line of output: withdraw still has a hole in it.
struct vs class
In C++, struct and class are identical except for default access:
// Two alternative definitions, not one filestruct Point { // members are public by default double x, y;};
class Point { // members are private by default double x, y;};Convention: struct for dumb bags of data, class when there are invariants to defend.
Methods
Methods are functions defined inside a class:
class Counter { int count = 0;public: void increment() { count++; } void decrement() { if (count > 0) count--; } int get() const { return count; }};The const qualifier on get() is a promise that the method won't touch the object. Const correctness in action — and the compiler holds you to it.
Defining Methods Outside the Class
Every method so far has been written inside the class body. That's fine for one-liners, but real classes usually split in two: the class definition, with declarations only, goes in a header, and the method bodies go in a .cpp file, each one qualified with the class name.
// counter.hclass Counter { int count = 0;public: void increment(); int get() const;};
// counter.cpp#include "counter.h"void Counter::increment() { count++; }int Counter::get() const { return count; }Counter:: tells the compiler which class the function belongs to, which is how the body can touch the private count. The const has to appear in both places, because it's part of the method's signature. A method defined inside the class body is implicitly inline, so the header can be included from many .cpp files without the linker seeing duplicate definitions.
Static Members and friend
A static data member belongs to the class, not to any one object. There's one copy, shared by every instance:
class Widget { static int live; // one counter for the whole class int id;public: Widget() : id(++live) {} ~Widget() { --live; } static int count() { return live; } // no object needed: Widget::count()};
int Widget::live = 0; // the one definition, in a .cpp fileA static method has no this, so it can only reach static members. Before C++17 the out-of-class definition line is required; from C++17 you can write static inline int live = 0; inside the class instead.
friend goes the other way and grants a named function or class access to the private members. You'll use it most for operators like <<, which the operator overloading lesson writes as free functions. Use it sparingly: every friend is one more piece of code that can break the invariants.
Predict: on a typical 64-bit system, what's sizeof(Widget)?
- Only
id, anint, is stored in eachWidget. The staticlivesits once in the program's data, and methods, static or not, are code, so they take no space in the object either. Add ten more methods and the answer stays 4.
this Pointer
Every method gets a hidden this pointer aimed at the current object:
class Builder {public: Builder &set_name(const std::string &name) { this->name = name; return *this; // return reference to self for chaining } Builder &set_value(int value) { this->value = value; return *this; }private: std::string name; int value;};
// Method chaining:Builder b;b.set_name("test").set_value(42);Each setter returns *this by reference, so the next call in the chain runs on the same object rather than a copy.
Worked Example: A Method Call, Unpacked
Here's what r.scale(2.0) amounts to once the compiler is done. The address is illustrative.
Rectangle r(3.0, 4.0); // say r lives at 0x7ffe2000r.scale(2.0);ris 16 bytes:widthat offset 0 (0x7ffe2000) holding 3.0, thenheightat offset 8 (0x7ffe2008) holding 4.0. That's the whole object. On x86-64,sizeof(Rectangle)is 16, the same as a C struct with twodoubles.scaleis compiled once, as an ordinary function that takes a hidden first parameter. In C terms it looks likevoid Rectangle_scale(Rectangle *this, double factor).- The call passes
&r, sothisis0x7ffe2000. On x86-64 Linux it travels inrdi, the first integer-argument register, withfactorinxmm0. width *= factoris reallythis->width *= factor: load thedoubleatthis + 0, multiply by 2.0, store 6.0 back.heightgoes the same way atthis + 8and becomes 8.0.r.area()now returns 6.0 × 8.0 = 48.
So a class costs nothing extra at runtime: data laid out like a struct, plus functions that receive a pointer to it. Access specifiers vanish entirely; private is a compile-time rule, not a runtime check. Objects in memory shows the real assembly.