Classes & Objects
Okay, this week is a game-changer. Up until now, you've been writing what's called procedural code — basically a bunch of functions floating around, operating on separate chunks of data. It works, but it gets messy fast. What if you could bundle the data and the functions that work on that data into one neat package? That's Object-Oriented Programming (OOP), and it's one of the most powerful ideas in all of programming.
Here's the key concept: a class is like a blueprint. Think of yourself as an architect. You draw up plans for a house — how many rooms, where the doors go, how the plumbing works. That's your class. An object is an actual house built from those plans. You can build 10 houses from the same blueprint, each painted a different color and at a different address, but they all share the same structure.
This week, we'll cover the building blocks of OOP:
- -Member variables (also called fields or attributes) — the data that lives inside each object
- -Member functions (also called methods) — the things an object can do
- -Access specifiers —
private(only the class itself can touch it),public(anyone can use it), andprotected(the class and its children can access it) - -Constructors — special functions that set up an object the moment it's created
- -Initializer lists — the efficient C++ way to set member values during construction
- -Encapsulation — hiding the messy internals and only showing a clean interface to the outside world
| Term | Meaning | Analogy |
|---|---|---|
| Class | Blueprint defining data + behavior | Architectural plan for a house |
| Object | A specific instance of a class | An actual house built from the plan |
| Member variable | Data stored in the object | Rooms, doors, windows in the house |
| Member function | Operations the object can perform | Turning on lights, opening doors |
| Constructor | Initializes the object when created | The construction crew that builds the house |
| Encapsulation | Hiding internals, exposing public interface | The house hides its plumbing behind walls |