| <<< Initializer list usage | Index | >>> |
Initializer list order should follow the order of data member declarations in your struct or class
Because constructor call order is very important, modern compilers will generate errors when initializer list does not follow the order of data members. For exaample,
struct Rectangle {
int width; // member variable
int height; // member variable
char* ptr_name;
Rectangle()
:
ptr_name( nullptr ), // out of order
height( 1 ), // out od order
width( 1 ) // out of order
{
set_name( "UNKNOWN" );
}
//...
};//struct Rectangle
When compiled with GNU GCC compiler, the above code will give you warning messages like this:
In constructor 'Rectangle::Rectangle()': 7:11: warning: 'Rectangle::ptr_name' will be initialized after [-Wreorder] 6:9: warning: 'int Rectangle::height' [-Wreorder] 9:5: warning: when initialized here [-Wreorder] 6:9: warning: 'Rectangle::height' will be initialized after [-Wreorder] 5:9: warning: 'int Rectangle::width' [-Wreorder] 9:5: warning: when initialized here [-Wreorder]
| <<< Initializer list usage | Index | >>> |