C/C++ Arena

Step 7 of 9

Member initializer lists

A constructor's initializer list (after the :) builds each member directly. Assigning inside the body instead first default-constructs the member and then overwrites it.

Player(std::string name, int hp) : name_(std::move(name)), hp_(hp) {}

Some members must be set in the initializer list, because they can't be assigned later:

Members are always initialized in the order they are declared in the class, not the order you list them. -Wall warns when the two orders differ (-Wreorder), because reading a member that isn't built yet is a real bug.

Your turn: give Player a constructor Player(const std::string& name, int max_hp) that sets the const name_, sets max_hp_, and starts hp_ at max_hp_. Use the initializer list for all three.

Previous: Challenge: a Clock class Next: Keeping invariants