Module 2 — Classes and Objects¶
After this module you can turn a bundle of related data into a C++ type that owns the operations on that data, and build a program from more than one file.
At a glance¶
| Prerequisites | Module 1 |
| Estimated study time | 6–8 hours |
| Lab | Lab 2 — first Book and Member classes |
| Exercises | Three tiers — warm-up, core, challenge |
| Cognitive levels | L1 Understand → L4 Analyze — exit level L3 Modify |
| Self-assessment | Module quiz |
Why this module matters¶
This is where the course's central idea becomes concrete: a type can carry its own behaviour. Until now, a record was a bag of fields and the functions that used it lived somewhere else, connected only by the discipline of passing the right variable to the right function. Nothing in the language stopped you from passing a book to a function expecting a member, or from forgetting one of the five parameters.
A class changes the shape of the problem. Instead of "here is some data, and
here are the functions that happen to operate on it", you get "here is a Book,
and it knows how to describe itself". The compiler now checks that you are using
it correctly, and the code that operates on books has a home.
You also learn the practical mechanics that every later module depends on: splitting a type into a header and a source file, and compiling more than one file at once.
Learning objectives¶
By the end of this module you will be able to:
- [L2 Apply] Declare a
classorstructwith data members and member functions. - [L1 Understand] State the only meaningful difference between
classandstructin C++ — default member access — and choose between them deliberately. - [L2 Apply] Create objects and access their members correctly, including objects inside a container.
- [L2 Apply] Use
public,privateandprotectedaccess specifiers, and explain what each controls. - [L1 Understand] Explain what
thisrefers to inside a member function, and name the two situations in which you need it. - [L1 Understand] Distinguish a class (a type) from an object (an instance), and explain why two objects of the same class have independent data.
- [L2 Apply] Define member functions inside the class body and outside it, and explain when the split is required.
- [L3 Modify] Take a working single-file program and rebuild it as a type in a header and a source file, built with one command.
- [L4 Analyze] Explain, in terms of
constandthis, why calling a non-constmember on aconstobject is an error — and whyconst_castis not the fix. - [L1 Understand] Explain how aggregate initialisation differs from construction, and why a type with a rule cannot be an aggregate.
This module's exit level is 3 Modify: you are finished when you can take a working single-file program and rebuild it as a type with a defended interface, split across files, building without a warning — not when you can recite the definitions.
Core concepts¶
- Class — a user-defined type. A blueprint, not a thing.
- Object — one instance of a class, with its own copy of the data members.
- Data member — a variable that belongs to each object.
- Member function — an operation that belongs to the class, with implicit access to the object it was called on.
- Access specifier —
public,private,protected: who may use a member. structvsclass— identical except the default access (publicforstruct,privateforclass) and the default inheritance mode.this— a pointer to the object a member function was called on. Needed when a parameter name hides a member name, and when returning the object itself.- Interface — the members that are
public: everything a caller is allowed to depend on. - Implementation — the
privatemembers and the bodies of the functions: everything a caller must be able to ignore. - Header / source split — the declaration lives in a header so many files can use it; the definition lives in one source file so it exists exactly once.
#pragma once/ include guards — prevent a header being pasted twice into one translation unit.- Aggregate initialisation — brace-initialising a simple
struct's members in order, without writing a constructor. constmember function — a member function that promises not to modify the object, and may therefore be called on aconstobject.- Object lifetime — an object begins to exist when it is created and stops existing at the end of its scope. Module 3 takes control of this.
Module contents¶
| Section | What it contains |
|---|---|
| Introduction (this page) | Overview, prerequisites, objectives, concept inventory |
| Concepts and explanations | Interface-first design, class vs struct, access control, this, const member functions, the header/source split, objects interacting |
| Worked examples | Five annotated programs plus one designed from nothing, each with a prediction prompt |
| Code examples | examples/module-02/ — five programs, four with captured output |
| Misconceptions and mistakes | Eight wrong mental models, seven real error messages |
| Debugging | The declaration/definition check, four full diagnoses, and the escalation ladder |
| Exercises | Three tiers, each stating its level and its success criterion |
| Lab 2 | The same program as Lab 1, rebuilt from types, plus a measured comparison |
| Challenge problems | Interface design on paper, a design review, and the leak hunt |
| Self-assessment | Nine questions, answers, and a re-test schedule |
| Summary | What must be retained, the terms to be able to define, and the checklist |
| Further reading | Books and official documentation |
What you can do after this module¶
- Model a real-world concept as a C++ type that keeps its data and its behaviour together.
- Decide what should be public and what should be private, and defend the choice.
- Organise a program across multiple files and build it.
- Recognise the difference between "this data is in a struct" and "this data should be protected by a type".
Where this is used later¶
- Access control becomes the whole subject of Module 4.
thisreturns immediately: it is needed foroperator=and is the reasonconst-qualified member functions exist.- The header/source split is used by every lab from here on, and becomes a full topic in Module 16.
- Object lifetime, introduced at the end of this module, is taken over by Module 3.
Common mistakes to watch for¶
| Symptom | Cause |
|---|---|
error: expected ';' after class definition |
Forgetting the semicolon after the closing } of a class |
error: 'x' is private within this context |
Reading or writing a private member from outside the class — by design |
undefined reference to Book::describe() const |
The member function is declared in the header but its body is never defined, or its source file was not included in the compile command |
| Two objects "sharing" a value | A member was declared static. static members are covered in Module 5 |
Skills checklist¶
Levels this module works at: [L1 Understand → L4 Analyze] — see How you will learn.
Tick an item only when the evidence exists:
- [ ] I can write a class whose data is private and whose operations express what the
system does — evidence: exercise C1's
Vehicle, with no accessor that nothing needed - [ ] I can state a type's invariant in one sentence — evidence: the invariant line in your Lab 2 interface table
- [ ] I can choose
structorclasson purpose — evidence: challenge X1's justification for aMoneytype - [ ] I can write
constmember functions — evidence: a program where aconst T¶meter compiles, and the error you got before addingconst - [ ] I can explain what
thisis and name both situations that need it — evidence: self-assessment question 7, answered without notes - [ ] I can split a type into a header and a source file and build it — evidence: exercise C4, built from one command, plus the link error you produced by omitting the source file
- [ ] I can tell a compile error from a link error in a multi-file program — evidence: the four predicted-and-observed messages from exercise C2
- [ ] I can make two types cooperate without either one owning the other's rule — evidence: exercise C5's duplicate-enrolment rule, with its owner named
Suggested next step¶
Previous: Module 1 — C++ and the OOP Mindset · Next: Module 3 — Constructors and Destructors · All modules: Modules index