Beginner level · Module 4: References, Pointers and First Classes · Lesson 3 of 3
Constructors and Keeping Objects Valid
Initialise objects with constructors and member initializer lists, and enforce rules in member functions.
In this lesson you will
- Write constructors with member initializer lists
- Validate input so objects never hold invalid data
Key concepts
constructormember initializer listinvariantstd::invalid_argument
The lesson
A constructor sets up a new object: WaterPoint(std::string name, double threshold) : name_{std::move(name)}, threshold_{threshold} {}. The member initializer list after the colon initialises members directly, which is more efficient than assigning in the body and required for const members and references.
An invariant is a rule that must always be true for an object, such as 'a reading is never negative'. Check rules in the constructor and in every member function that changes data; reject invalid values with throw std::invalid_argument("reading must be >= 0");.
If you write no constructor, the compiler provides a default one that may leave built-in members uninitialised. Give members default values in the class, such as double reading_{0.0};, to avoid that.
Step by step
- Add a constructor with an initializer list to WaterPoint.
- Reject a negative threshold in the constructor.
- Reject negative readings in recordReading.
- Test valid and invalid cases from main.
Practice activity
Complete the WaterPoint practical: points below the threshold are flagged for repair, and invalid readings are rejected.
Expected result: Valid readings update the object, invalid ones throw with a clear message, and flagged points are listed correctly.
Check your understanding
-
What is a member initializer list?
Show answer
The list after the constructor's colon that initialises members directly.
-
What is an invariant?
Show answer
A rule that must always hold for an object's data.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.