Analysis of the initialization list in C ++ (difference assignment and initialization)
The derived class cannot directly access the Private Members of the base class, but must be accessed through the base class method.
Specifically, the derived class constructor must use the base class constructor.
When creating a derived class object, the program first creates a base class object. C ++ uses the initialization list to complete this task.
RatedPlayer::RatedPlayer(int r, const string &fn):TableTennisPlayer(fn){ rating = r;}
TableTennisPlayer (fn) is the member initialization list, which is executable code. Call the TableTennisPlayer constructor.
If the initialization list is not used, the base class default constructor is called.
Similarly, you can use the member initialization list syntax for the derived class members:
RatedPlayer::RatedPlayer(int r, const string &fn):TableTennisPlayer(fn),rating(r){}
Key points about the derived class constructor:
1. Create a base class object.
2. The derived class constructor should pass the base class information to the base class constructor through the member initialization list.
3. The derived class constructor should initialize the new data member of the derived class.
In Objective C ++, "Make sure that objects are initialized before they're used." is written, that is, "the object is initialized before it is used ".
Inheritance is not discussed below.Assignment and initialization! The Code is as follows:
ABEntry::ABEntry(const std::string & name){ theName = name;}
C ++ rules,The initialization action of the object's member variables takes place before entering the constructor body..
Therefore, in the appeal code, theName is assigned a value instead of initialization. That is, the default constructor of this class is called first, and then the theName is assigned to the name, that is, the copy constructor is called.
Change the appeal code:
ABEntry::ABEntry(const std::string & name): theName(name){}
Only the default constructor is called, and the copy constructor is no longer called.
Therefore, the higher the program efficiency when initializing the list with members !!