The constructor method is used to initialize class objects. Unlike other members of the parent class, it cannot be inherited by the subclass (a subclass can inherit all member variables and member methods of the parent class, but does not inherit the parent class's constructor methods). Therefore, when creating a subclass object, in order to initialize the data members inherited from the parent class, the system needs to call the parent class's constructor methods.
If there is no explicit constructor, the compiler will provide a default constructor, and this default constructor is created only when no constructor is explicitly declared.
The construction principles are as follows:
- 1. If the subclass does not define a constructor method, the parent class's no-argument constructor method is called.
- 2. If the subclass defines a constructor method, whether it has no arguments or with arguments, when creating an object of the subclass, the parent class's no-argument constructor method is executed first, and then its own constructor method is executed.
- 3. When creating a subclass object, if the subclass's constructor does not explicitly call the parent class's constructor, the parent class's default no-argument constructor will be called.
- 4. When creating a subclass object, if the subclass's constructor does not explicitly call the parent class's constructor and the parent class itself provides a no-argument constructor, the parent class's own no-argument constructor will be called.
- 5. When creating a subclass object, if the subclass's constructor does not explicitly call the parent class's constructor and the parent class only defines its own parameterized constructor, an error will occur (if the parent class only has a parameterized constructor, the subclass must explicitly call this parameterized constructor method).
- 6. If the subclass calls the parent class's parameterized constructor, it needs to do so by initializing the parent class member object, for example:
Example
After the fish class constructor, add a colon:, then add the parent class's parameterized constructor. In this way, when the subclass's constructor is called, the system will call the parent class's parameterized constructor to construct the object.
Exceptions like the common MFC CDialog inheritance can be seen in such examples..
Example
Implementation file
Example
This initialization method is also often used to initialize constant (const) members of a class, as shown in the following code:
Example
Of course, ordinary member variables in a class can also be initialized in this way, but there is no need to do so..
Source: http://blog.jobbole.com/109500/