CodeBlanks Logo Icon CodeBlanks

Member initializer list

Learn efficient initialization with the member initializer list.

Member initializer list

A more efficient way to initialize member variables in C++ is the member initializer list. After the constructor's parameter parentheses, a colon is placed, then each member is written as member(value).

Example: Player(std::string n, int l) : name(n), level(l) { }. Here name(n) initializes the name member with n; it does not assign. With assignment in the body, the member would first be default-constructed and then overwritten. The initializer list removes this double work; it is required for const and reference members.

Initialization order

Members are initialized in the order they are declared in the class, not the order in the initializer list. So even if you write : level(l), name(n), name is constructed first, then level. Keeping the order consistent with the class definition avoids warnings.

The order matters when one member uses another in the list. Example: : name(n), level(name.length()). If level is declared before name, level would try to use an uninitialized name. So pay attention to declaration order for dependent initializations.

Practice Add a member initializer list to the Player class

Define a Player class. Under public: add std::string name; and int level; member variables. Write the constructor Player(std::string n, int l) : name(n), level(l) { } with an initializer list. In main create Player p("Alex", 5); and print name with std::cout.

Starter code

main.cpp
#include <iostream>
#include <string>

// Define the Player class here

int main() {
    // Create a Player instance with an initializer list and print name
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <string>

class Player {
public:
    std::string name;
    int level;
    Player(std::string n, int l) : name(n), level(l) {
    }
};

int main() {
    Player p("Alex", 5);
    std::cout << p.name;
    return 0;
}

Expected output

Alex

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each piece to its role

Term Meaning
: name(n) initializes the name member
name(n), level(l) comma-separated list
{ } constructor body
Player(std::string n, int l) parameter list

2 Write the colon

Question
Player(std::string n) ____ name(n) { }
Answer
Player(std::string n) : name(n) { }

Explanation: The colon starts the initializer list.

3 Which of these initializer lists is correct?

main.cpp
Player(std::string n, int l)
  • Player(std::string n, int l) { name(n), level(l) }
  • Player(std::string n, int l) : name(n) level(l) { }
  • Player(std::string n, int l) = name(n), level(l);
  • Player(std::string n, int l) : name(n), level(l) { } Correct answer

Explanation: Colon, comma-separated members and body in the right order.

All lessons in Intermediate