Skip to main content
Be Bitwise

Classes & Objects

Classes & Object-Oriented Programming · Coding Fundamentals track

8 min read

In this module

Grouping Data and Behaviour

So far you've worked with individual variables and collections of data. Real-world concepts are messier than that. A "user" bundles a name, an email, an age, a list of permissions, and behaviours like "log in" and "change password." A "rectangle" is more than two numbers; it has a width and a height plus operations like "calculate area" and "resize."

Object-oriented programming (OOP) is a paradigm that lets you bundle related data and the functions operating on that data into a single unit. The blueprint for that unit is a class. A concrete instance of the class is an object.

text
class Dog {
name
breed
age
function bark() {
print(name + " says: Woof!")
}
function describe() {
print(name + " is a " + breed + ", age " + age)
}
}

This class lays out what every Dog has (name, breed, age) and what every Dog can do (bark, describe). The class itself is just the blueprint, though.

Creating Objects

To get an actual dog, you instantiate the class:

text
my_dog = new Dog()
my_dog.name = "Rex"
my_dog.breed = "Labrador"
my_dog.age = 3
my_dog.bark() // Rex says: Woof!
my_dog.describe() // Rex is a Labrador, age 3

Each object owns its own copy of the data fields. Spin up another Dog and it has its own name, breed, and age, independent of the first.

text
other_dog = new Dog()
other_dog.name = "Luna"
other_dog.breed = "Poodle"
other_dog.age = 5
other_dog.bark() // Luna says: Woof!
Key Concept

A class is a blueprint that defines data fields and methods. An object is an instance of a class with its own data. You can create many objects from one class, each with different values but the same structure and behaviour.

Constructors

Most languages give you a special method called a constructor that initialises an object's state at the moment of creation. Rather than setting fields one by one after the fact, the constructor takes the initial values as parameters and wires them up.

text
class Dog {
name
breed
age
constructor(name, breed, age) {
this.name = name
this.breed = breed
this.age = age
}
function bark() {
print(this.name + " says: Woof!")
}
}
my_dog = new Dog("Rex", "Labrador", 3)
my_dog.bark() // Rex says: Woof!

The keyword this (or self in some languages) refers to the current object — the specific instance whose method is being called right now.

Methods: Functions That Belong to Objects

Functions defined inside a class are called methods. They reach the object's data through this/self. Methods are the "behaviour" half of a class — they spell out what the object can do.

text
class BankAccount {
owner
balance
constructor(owner, initial_balance) {
this.owner = owner
this.balance = initial_balance
}
function deposit(amount) {
this.balance = this.balance + amount
}
function withdraw(amount) {
if amount > this.balance {
print("Insufficient funds")
return
}
this.balance = this.balance - amount
}
function get_balance() {
return this.balance
}
}

Methods wrap up the logic that manipulates an object's state. Rather than poking at balance directly from the outside, you call deposit and withdraw, which can enforce rules — like refusing to let the balance go negative.

C has no classes, so it shows what a method boils down to. The struct holds the fields, and each "method" is an ordinary function whose first parameter is a pointer to the object, which is the this that OOP languages pass for you.

Try itAdd a birthday(struct dog *self) function that increments the age, call it on one dog, and check the other dog is unchanged.
C (GCC 9.2.0)

Objects in Memory

When you create an object, the system allocates a block of memory (usually on the heap) large enough for all the object's fields. The fields sit contiguously, much like a C struct.

text
my_dog = new Dog("Rex", "Labrador", 3)
Memory layout of my_dog:
+--------+-----------+-----+
| name | breed | age |
| "Rex" | "Labrador"| 3 |
+--------+-----------+-----+

The variable my_dog is actually a reference (a pointer) to that block of memory. When you call my_dog.bark(), the system follows the pointer to find the object's data, then calls the bark method with this pointing to that memory.

This is the pointer concept (which gets a module of its own later) dressed up. Object references are pointers wearing nicer syntax.

Here's the same Dog the way a C-like language with 8-byte pointers would lay it out. Strings are usually too big and too variable to live inside the object, so name and breed hold the addresses of their text, stored somewhere else. Every field sits at a fixed offset, so my_dog.age compiles to "the address in my_dog, plus 16". Make a second Dog and it gets its own 24-byte block with its own copies of all three fields.

One Dog object

0x00x18
OffsetFieldSizeNotes
0x0 (0)char* name8Address of "Rex"
0x8 (8)char* breed8Address of "Labrador"
0x10 (16)int age43, stored right here
0x14 (20)padding4

sizeof = 24 bytes, 4 of them padding; alignment 8.

Classes as Custom Types

A class is, in essence, a way to mint your own data type. The language hands you integers and strings out of the box; classes let you define types meaningful to your specific problem — User, Invoice, GameCharacter, NetworkConnection.

Once defined, your class type works anywhere a type is allowed: variable declarations, function parameters, return types, or elements in a collection.

text
function oldest_dog(dogs) {
result = dogs[0]
for dog in dogs {
if dog.age > result.age {
result = dog
}
}
return result
}

This function works with Dog objects as naturally as another function would work with integers. The ability to define your own types and operations is one of OOP's most powerful features.

From Hardware to Objects

At the machine level, an object is a chunk of memory holding fields laid out sequentially. Accessing dog.name becomes a memory read at the object's base address plus the offset of the name field. Methods are functions that receive a hidden pointer to the object (commonly called this or self) as their first argument. No magic involved. OOP is an abstraction layer sitting on top of the same memory and function calls you've been studying all course. Holding that mapping in your head helps you reason about performance and trace bugs that come down to how objects sit in memory.