Why initialize member variables of a class using initialization list?
在创建一个类的一个实例(object)时,如果不用初始化列表做成员变量(member variable)的初始化,那么每个成员变量先调用各自的default constructor做初始化,然后用赋值操作赋值。用初始化列表做初始化,直接调用 copy constructor对各成员变量做初始化,更高效。详细请看下面的例子:
class Author
{
public:
Author();
Author(const string &name);
private:
string name_;
};
Author::Author() : name_("NONAME")
{
printf("Author: default constructor is called\n");
}
Author::Author(const string &name) : name_(name)
{
printf("Author: alt constructor is called\n");
}
class Book
{
public:
Book();
Book(const string &name, int id, const Author &author);
private:
string name_;
int id_;
Author author_;
};
// Default constructor
Book::Book(): name_(), id_(), author_()
{
printf("Book: Default constructor is called\n");
}
// Constructor, no initialization list
Book::Book(const string &name, int id, const Author &author) {
printf("Book: alt Constructor is called\n");
name_ = name;
id_ = id;
author_ = author;
}
As initialization list is not available, before entering the body of constructor, all member variables of a class will be automatically initialized by their default constructors.
Inside the constructor, member variables (name_, author_) are assigned with new value in argument list.
Thus, a call of the default constructor and an assignment operation are taken to assign a value to each member variable in the creation of a new object.
Note if the default constructor of one member variable is not defined, a error will be incurred.
// Constructor, initialize class member variables using initialization list
Book::Book(const string &name, int id, const Author &author)
: name_(name), id_(id), author_(author)
{
printf("Book: better alt constrcutor is called\n");
}
A single call to copy constructor is used to initialize a member variable in the initialization list. Thus the call of the default constructor is avoided.
For most types, a single call to a copy constructor is more efficient – sometimes much more efficient – than a call to the default constructor followed by a call to the copy assignment operator.
int main()
{
Author author("Li Q");
string name("Learning OOP");
int id = 9;
Book b(name, id, author);
return 1;
}