Skip to content

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:

  1. [L2 Apply] Declare a class or struct with data members and member functions.
  2. [L1 Understand] State the only meaningful difference between class and struct in C++ — default member access — and choose between them deliberately.
  3. [L2 Apply] Create objects and access their members correctly, including objects inside a container.
  4. [L2 Apply] Use public, private and protected access specifiers, and explain what each controls.
  5. [L1 Understand] Explain what this refers to inside a member function, and name the two situations in which you need it.
  6. [L1 Understand] Distinguish a class (a type) from an object (an instance), and explain why two objects of the same class have independent data.
  7. [L2 Apply] Define member functions inside the class body and outside it, and explain when the split is required.
  8. [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.
  9. [L4 Analyze] Explain, in terms of const and this, why calling a non-const member on a const object is an error — and why const_cast is not the fix.
  10. [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.
  • struct vs class — identical except the default access (public for struct, private for class) 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 private members 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.
  • const member function — a member function that promises not to modify the object, and may therefore be called on a const object.
  • 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.
  • this returns immediately: it is needed for operator= and is the reason const-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 struct or class on purpose — evidence: challenge X1's justification for a Money type
  • [ ] I can write const member functions — evidence: a program where a const T& parameter compiles, and the error you got before adding const
  • [ ] I can explain what this is 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