Course list http://www.c-jump.com/bcc/
Compare two versions of the Rectangle struct constructors:
|
|
Initializer list is a preferred constructor syntax by most professionals for member initialization.
Initializer list must be used for:
References
Data members without default constructors
const member variables
If you do not explicitly initialize a data member in the initializer list, the compiler automatically initializes it using member's default constructor. For objects without default constructor this will be an error.
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]