Lesson 2 of 7
Constructors - Member Initialiser List & Delegating
The **member initialiser list** (after `:` before `{`) is the correct place to initialise member variables - it is executed before the constructor body. Using assignment inside the body (`m_value = x;`) is a two-step: default-construct then assign. MIL is one-step: direct-construct. For `const` members, reference members, and members with no default constructor, the MIL is the **only** option. **Delegating constructors** (C++11) allow one constructor to call another, reducing code duplication.
Member Initialiser List, Delegating & Default Constructors
#include <iostream>
#include <string>
#include <stdexcept>
class Person {
const std::string name_; // const - MUST be in MIL
int& age_ref_; // reference - MUST be in MIL
std::string email_;
int score_;
public:
// ── Primary constructor - full MIL ────────────────────────
Person(std::string name, int& age, std::string email, int score)
: name_(std::move(name)) // moves string - no copy
, age_ref_(age) // binds reference
, email_(std::move(email))
, score_(score)
{
// body: validation only (members already initialised)
if (score_ < 0 || score_ > 100) {
throw std::out_of_range("Score must be 0-100");
}
std::cout << "Constructed: " << name_ << "
";
}
// ── Delegating constructor (C++11) ────────────────────────
// Calls the primary constructor with a default email
Person(std::string name, int& age, int score)
: Person(std::move(name), age, "none@example.com", score)
{} // delegated - this body runs AFTER the target constructor
// ── Default/delete - control implicit generation ───────────
Person() = delete; // prevent default construction
// Person(const Person&) = default; // use compiler-generated copy
// ── Getters ───────────────────────────────────────────────
const std::string& name() const { return name_; }
int age() const { return age_ref_; } // reads from ref
const std::string& email() const { return email_; }
int score() const { return score_; }
};
// ── Member initialisation order - ALWAYS follows declaration order ──
class OrderDemo {
int a_; // initialised first regardless of MIL order
int b_; // initialised second
public:
// WRONG (but compiles): MIL order ≠ declaration order
// OrderDemo(int x) : b_(x), a_(b_ * 2) {}
// Undefined behaviour: b_ not yet initialised when a_ reads it!
// CORRECT: match MIL to declaration order
OrderDemo(int x) : a_(x), b_(a_ * 2) {} // safe when order matches
void print() const { std::cout << a_ << " " << b_ << "
"; }
};
int main() {
int age = 30;
Person p1{"Alice", age, "alice@example.com", 95};
Person p2{"Bob", age, 72}; // delegating constructor
std::cout << p1.name() << " email=" << p1.email() << "
";
std::cout << p2.name() << " email=" << p2.email() << "
";
age = 31;
std::cout << "p1 age via ref: " << p1.age() << "
"; // 31 (reference!)
OrderDemo od(5);
od.print(); // 5 10
// Score out of range throws
try {
Person bad{"X", age, 200};
} catch (const std::out_of_range& e) {
std::cerr << "Caught: " << e.what() << "
";
}
return 0;
}Common Mistakes
- Member initialisation order follows declaration order, not MIL order - if `a_` is declared before `b_`, then `a_` is always initialised first, even if MIL says `: b_(0), a_(b_)`. Reading `b_` to initialise `a_` gives undefined behaviour if `b_` is declared after `a_`. Always order MIL to match declaration order.
- Initialising in the constructor body for non-trivial types - `email_ = std::move(email)` in the body first default-constructs `email_` (empty string), then move-assigns. Using the MIL directly constructs it. For `std::string`, the difference is trivial, but for large objects it matters.
- Delegating constructors cannot have other initialisers - `Person(std::string n, int& a) : Person(std::move(n), a, ...), extra_field_(0) {}` - once a constructor delegates, it cannot initialise any other member. All initialisation must happen in the target constructor.
Tip
Tip
Practice Constructors Member Initialiser List Delegating in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Default, Parameterized, Delegating Constructors & Direct In-Place Initialization
Practice Task
Note
Practice Task - (1) Write a working example of Constructors Member Initialiser List Delegating from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Constructors Member Initialiser List Delegating is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.
Key Takeaways
- The **member initialiser list** (after `:` before `{`) is the correct place to initialise member variables - it is executed before the constructor body.
- Member initialisation order follows declaration order, not MIL order - if `a_` is declared before `b_`, then `a_` is always initialised first, even if MIL says `: b_(0), a_(b_)`. Reading `b_` to initialise `a_` gives undefined behaviour if `b_` is declared after `a_`. Always order MIL to match declaration order.
- Initialising in the constructor body for non-trivial types - `email_ = std::move(email)` in the body first default-constructs `email_` (empty string), then move-assigns. Using the MIL directly constructs it. For `std::string`, the difference is trivial, but for large objects it matters.
- Delegating constructors cannot have other initialisers - `Person(std::string n, int& a) : Person(std::move(n), a, ...), extra_field_(0) {}` - once a constructor delegates, it cannot initialise any other member. All initialisation must happen in the target constructor.
Finished this lesson?