1.2.3.3 initializer list
  • Always use initializer list instead of assignment inside ctor.
  • When to use member initalize list, you can see in this link:
    1. to non-static const data members.
    2. reference member
    3. member objects which do not have default constructor: (why I need default ctor can be explained here too)
    4. need pass argument to base class ctor
      class A { 
          int i; 
      public: 
          A(int ); 
      }; 
       
      // Class B is derived from A 
      class B: A { 
      public: 
          B(int ); 
      }; 
       
      B::B(int x):A(x) { //Initializer list must be used 
          cout << "BsConstructorcalled"; 
      }
    5. need to by copy between obj to member obj. (only one copy ctor, more efficient! see below source code.)
    http://www.geeksforgeeks.org/when-do-we-use-initializer-list-in-c/

    //method 1: 
    class(string &a, string &b): m_a(a),m_b(b){} 
    // just call string copy ctor, 
    //so you dont need string default ctor 
     
    //method 2: 
    class(string &a, string &b){   // two action. 
    m_a = a;  //call default constructor to build m_a 
    m_b = b; // then call assignment operator. 
    }
  • List member in a initialization list in the order in which they are declared in class. see effective c++ item 13. Order is important.
  • Member variables are always initialized in the order they are declared in the class definition. The order in which you write them in the ctor initialization list is ignored. So you’d better not have one member’s initialization depend on other members.
    class Student{ 
    string m_email;  //m_email will be init first, ingore order 
    string m_first_name;  // in the ctor initialization list. 
    Student(first_name) :m_first_name(first_name), 
                    m_email(m_first_anme+"@gmail"){}
  • If GetType() is a static member function, or a member function that does not use its this pointer (that is, uses no member data) and does not rely on any side effects of construction (for example, static usage counts), then this is merely poor style, but it will run correctly.

    Otherwise (mainly, if GetType() is a normal nonstatic member function), we have a problem. Nonvirtual base classes are initialized in left-to-right order as they are declared, so ArrayBase is initialized before Container. Unfortunately, that means we’re trying to use a member of the not-yet-initialized Container base subobject.

    template<class T> 
    class Array : _____________________________________________________________________private ArrayBase, public Container 
     
    typedef Array AIType; 
    public: 
    Array( size_t startingSize = 10 ) 
    : Container( startingSize ), 
    ArrayBase( Container::GetType() ),