Course list http://www.c-jump.com/bcc/

C++ constructor initializer list


  1. Initalizer list example
  2. Initializer list usage
  3. Initializer list order

1. Initalizer list example


  • Constructors not using the initalizer lists:

    
    struct Rectangle {
        int width;  // member variable
        int height; // member variable
        char* ptr_name;
        Rectangle()
        {
            width = 1;
            height = 1;
            ptr_name = nullptr;
            set_name( "UNKNOWN" );
        }
        Rectangle( char const* ptr_name_, int width_  )
        {
            width = width_;
            height = width_;
            ptr_name = nullptr;
            set_name( ptr_name_ );
        }
        Rectangle( char const* ptr_name_, int width_ , int height_ )
        {
            width = width_;
            height = height_;
            ptr_name = nullptr;
            set_name( ptr_name_ );
        }
        //...
    };//struct Rectangle
    
    
  • Constructors using the initalizer lists:

    
    struct Rectangle {
        int width;  // member variable
        int height; // member variable
        char* ptr_name;
        Rectangle()
            :
            width( 1 ),
            height( 1 ),
            ptr_name( nullptr )
        {
            set_name( "UNKNOWN" );
        }
        Rectangle( char const* ptr_name_, int width_  )
            :
            width( width_ ),
            height( width_ ),
            ptr_name( nullptr )
        {
            set_name( ptr_name_ );
        }
        Rectangle( char const* ptr_name_, int width_ , int height_ )
            :
            width( width_ ),
            height( height_ ),
            ptr_name( nullptr )
        {
            set_name( ptr_name_ );
        }
        //...
    };//struct Rectangle
    
    

2. Initializer list usage



3. Initializer list order