When to Use Member Initializer Lists

What are the benefits of using member initializer lists in constructors?

Member initializer lists provide several benefits over assigning values in the constructor body:

  1. Performance: Initializing members in the initializer list directly constructs them with the provided values. Assigning values in the constructor body first default-constructs the members, then assigns to them. This can be less efficient, especially for complex types.
  2. Const and Reference Members: Const and reference members MUST be initialized in the member initializer list, as they cannot be assigned to later.
  3. Clarity: Initializer lists make it clear which arguments are being used to initialize which members. This can make the code more readable.

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.

Classes, Structs and Enums

A crash tour on how we can create custom types in C++ using classes, structs and enums

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

When to Use Classes vs Structs in C++
What are the key differences between classes and structs in C++, and when should I use one over the other?
Multiple Constructors with the Same Name
How can a class have multiple constructors with the same name?
When to Use Public Inheritance
In what situations is it appropriate to use public inheritance in C++?
Implicitly-Defined Default Constructors
When does the compiler implicitly define a default constructor for a class?
Using Destructors for Resource Management
How can I use destructors to manage resources in C++?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant