Initialize members before the constructor body
A member initializer list appears after a constructor's parameter list and before its body. It constructs base classes and members directly. Assignment inside the body happens later, after those subobjects have already been initialized.
A class with fixed identity
#include
#include
#include
class Student {
const int roll_;
std::string name_;
public:
Student(int roll, std::string name)
: roll_{roll}, name_{std::move(name)} { }
void print() const {
std::cout << roll_ << ' ' << name_ << '\n';
}
};
int main() {
Student student{101, "Asha"};
student.print();
} Expected output: 101 Asha. roll_ is const and must be initialized, not assigned later. The string is constructed from the provided name. This example does not validate the roll; a real invariant requiring positive roll numbers should be checked during construction.
Actual initialization order
Base subobjects initialize before ordinary members. Members initialize in the order they are declared in the class, regardless of the order written in the initializer list. Write the list in declaration order to make that dependency visible.
class Buffer {
std::size_t size_;
std::vector values_;
public:
explicit Buffer(std::size_t size) : size_{size}, values_(size_) { }
}; This fragment requires cstddef and vector. size_ is ready before values_ uses it. Reversing the member declarations while leaving the initializer list unchanged would introduce a dangerous dependency on an uninitialized value.
Members that require initialization
Const members, reference members and members without an accessible default constructor generally need suitable initialization. A reference member also creates a lifetime obligation: the referred-to object must outlive the containing object's use of it. An initializer list does not solve a dangling-reference design.
Braces and parentheses differ for containers
std::vector creates three elements, each 7. std::vector creates two elements, 3 and 7, because the initializer-list constructor is selected. Choose syntax according to the constructor you intend.
Exercises
- Add a marks member initialized to zero unless explicitly supplied.
- Explain why
roll_ = roll;in the body cannot initialize a const member. - Predict the sizes of the two vectors above. Answers: 3 and 2.
- Create a class whose second member depends on the first, then verify that declarations and initializer list show the same order.