Member initializer lists provide several benefits over assigning values in the constructor body:
Here's an example:
#include <string>
class Player {
public:
Player(const std::string& name, int health)
: name_{name}, health_{health} {}
private:
std::string name_;
int health_;
};
Without the initializer list, we would have to write:
Player::Player(const std::string& name, int health) {
name_ = name;
health_ = health;
}
This is less efficient, as name_
will be default-constructed first, then assigned to.
So prefer initializer lists, especially for const/reference members and complex types. Use assignment in the constructor body only when the initialization depends on some computation that can't be done in the initializer list.
Answers to questions are automatically generated and may not have been reviewed.
A crash tour on how we can create custom types in C++ using classes, structs and enums