# A ten hour bug For the last four weeks I've been going through a long overdue refactor of a critical component built on top of a poorly written OSS codebase (and contemplated a visit to the rope store many times during the process). The final changelist contained 300+ files, mostly written from scratch. Among things which trully needed fixing, it was filled with harmless little snippets like this: ```cpp= double x = Read<double>(&file); double y = Read<double>(&file); double z = Read<double>(&file); Eigen::Vector3d xyz; xyz(0) = x; xyz(1) = y; xyz(2) = z; ``` Which really set off my OCD (use a constructor, those doubles can be `const auto`, etc.). So I would routinely rewrite them into bits that looked more like this: ```cpp= const Eigen::Vector3d xyz( Read<double>(&file), Read<double>(&file), Read<double>(&file)); ``` It's shorter, less code to copy/paste, on to the next bit. Right? Well, wrong. At least in this example, that is. Initialization order is a thing in C++ and just beacuse I wrote each method in its own line doesn't mean they will execute in that order (at least not if they're constructor arguments). Anyway, here's what the C++ standard has to say on the topic (or to be completely accurate, what some guy on [StackOverflow](https://stackoverflow.com/a/4037283) copied from the standard when asked about this topic): >Initialization shall proceed in the following order: > * First, and only for the constructor of the most derived class as described below, virtual base classes shall be initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where “left-to-right” is the order of appearance of the base class names in the derived class base-specifier-list. > * Then, direct base classes shall be initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers). > * Then, nonstatic data members shall be initialized in the ***order they were declared in the class definition (again regardless of the order of the mem-initializers)***. > * Finally, the body of the constructor is executed. Here's a [toy example](https://onlinegdb.com/S1BdAJyOd) you can play around with to test this out. The moral of the story should be not to rely on ctor execution order because: 1. It's not always obvious to the user. You have to take a look at the class declaration to be sure. 2. Member definition order can be altered by anyone at any point in the future without breaking the build, but breaking execution. However, the moral of the story for me personally is to focus more on the code I'm refactoring and not let my OCD run wild.