Original Post
The following is said in programming gems 2:
quote:What if I do more in the constructor then only assigning name to nName? What if I have more assignments to member variables? Should I still be following this tip? TIA, Michel
Consider the following class: class Vehicle { public: Vehicle(const std::string &name) // Don''t do this! { mName = name; } private: std:: string mName; }; Because member variables are constructed before the body of the constructor is invoked, this code calls the constructor for the string mName, and then calls the = operator to copy in the object''s name. What''s particularly bad about this example is that the default constructor for string may well allocate memory — in fact, more memory than may be necessary to hold the actual name assigned to the variable in the constructor for Vehicle. The following code is much better, and avoids the call to operator =. Further, given more information (in this case, the actual string to be stored), the nondefault string constructor can often be more efficient, and the compiler may be able to optimize away the Vehicle constructor invocation when the body is empty: class Vehicle { public: Vehicle(const std::string &name) : mName(name) {} private: std::string mName; };