Skip to content

Last updated:2026-10-12

C++ Member Initializer List Pitfalls

In C++, correctly initializing a class is one of the key steps to ensure a program runs correctly. This is especially true when using initializer lists: we need to watch out for some potential traps to avoid unexpected results during code execution.

The initializer list is generally considered the preferred way to set up the state of a new class instance, because it provides a concise, efficient way to initialize class members. However, referring to other member variables in the initializer list can sometimes lead to confusing problems.

Problem Example

Consider the following Foo class:

#include <iostream>

class Foo
{
public:
  Foo(int size) : size_(size),
                 capacity_(size_ + 2),
                 length_(capacity_)
  {}

  void print() {
    std::cout << "Size: " << size_ << " Capacity:  " << capacity_ << " Length: " << length_  << std::endl;
  }

private:
  int length_;
  int capacity_;
  int size_;
};

int main() {
  Foo foo(50);
  foo.print();
}

In this example, we try to initialize length_, capacity_, and size_ by referring to other member variables in the initializer list. However, because class members are initialized in the order in which they are declared in the class, length_ and capacity_ may not be initialized the way we expect.

How to Solve It?

To avoid this kind of problem, you should follow these points:

1. Avoid referring to other member variables in the initializer list

2. Order consistency: member variables are initialized in the order in which they are declared in the class

Corrected example:

#include <iostream>

class Foo
{
public:
  Foo(int size) : size_(size),
                 capacity_(size_ + 2),
                 length_(calculateLength(size_))
  {}

  void print() {
    std::cout << "Size: " << size_ << " Capacity:  " << capacity_ << " Length: " << length_  << std::endl;
  }

private:
  int calculateLength(int size) {
    return size + 2;
  }

private:
  int size_;
  int capacity_;
  int length_;
};

int main() {
  Foo foo(50);
  foo.print();
}

Comments