Classes, Structs and Enums

When to Use Member Initializer Lists

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

Abstract art representing computer programming

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.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved