Skip to main content
Be Bitwise
C++Classes & OOP

Class Basics

Classes are where C++ object orientation lives. Data and the functions that act on it, packaged together.

Defining a Class

cpp
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

0x00x10
OffsetFieldSizeNotes
0x0 (0)double width8this + 0
0x8 (8)double height8this + 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 for class)
  • public - accessible from anywhere
  • protected - accessible inside the class and its subclasses
Key Concept

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.

Try itUncomment the direct write to balance, read the compiler error, then make withdraw refuse amounts of zero or less.
C++ (GCC 9.2.0)

struct vs class

In C++, struct and class are identical except for default access:

cpp
// Two alternative definitions, not one file
struct 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:

cpp
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.

cpp
// counter.h
class 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:

cpp
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 file

A 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)?
  1. Only id, an int, is stored in each Widget. The static live sits 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:

cpp
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.

cpp
Rectangle r(3.0, 4.0); // say r lives at 0x7ffe2000
r.scale(2.0);
  1. r is 16 bytes: width at offset 0 (0x7ffe2000) holding 3.0, then height at 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 two doubles.
  2. scale is compiled once, as an ordinary function that takes a hidden first parameter. In C terms it looks like void Rectangle_scale(Rectangle *this, double factor).
  3. The call passes &r, so this is 0x7ffe2000. On x86-64 Linux it travels in rdi, the first integer-argument register, with factor in xmm0.
  4. width *= factor is really this->width *= factor: load the double at this + 0, multiply by 2.0, store 6.0 back. height goes the same way at this + 8 and becomes 8.0.
  5. 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.