Member initializers list method can be used to initialize data members using class constructors. Let’s understand this with the help of an example,

#include <iostream>
 
class Point
{
    int m_x{};
    int m_y{};
 
public:
    Point(int x, int y)
        : m_x{x}, m_y{y}
    {
        std::cout << "Constructor Point(" << x << ", " << y << ")\n";
    }
 
    void print() const
    {
        std::cout << "{" << m_x << ", " << m_y << "}\n";
    }
};
 
int main(int argc, char const *argv[])
{
    const Point point{1, 2};
 
    point.print();
    return 0;
}

Initializations are defined after the constructor parameters, starting with colon (:) followed by the list of initializations.

Initialization order

Initialization order follows the order data members are defined in the class irrespective the order of initializations in member initializations list. For example,

Point(int x, int y)
        : m_y{y}, m_x{x}
    {
        std::cout << "Constructor Point(" << x << ", " << y << ")\n";
    }

would still initialize m_x first.

Constructor body

Once the initialization list is executed, constructor function body is executed. Some developers may do following in constructor to initialize data members,

Point(int x, int y)
        : m_x{x}, m_y{y}
    {
        m_x = x;
        m_y = y;
        std::cout << "Constructor Point(" << x << ", " << y << ")\n";
    }

it is assignment not the initialization. If m_x and m_y are const members, the assignment will fail.

So, always prefer using member initialization list over assignment in constructor body.

References

  1. https://www.learncpp.com/cpp-tutorial/constructor-member-initializer-lists/