Subclass call the parent class constructor when creating an object:
1 #include <iostream> 2 using namespace std; 3 class Base 4 { 5 public: 6 Base():m_num(0){ 7 cout<<"this is Base()"<<endl; 8 } 9 Base(int val):m_num(val){ 10 cout<<"this is Base(int val)"<<endl; 11 } 12 private: 13 int m_num; 14 }; 15 16 class BaseChild:public Base 17 { 18 public: 19 BaseChild(){ 20 cout<<"this is BaseChild()"<<endl; 21 } 22 BaseChild(int val):Base(val){ 23 cout<<"this is BaseChild(val)"<<endl; 24 } 25 }; 26 27 int main(intargc is, char * argv is []) 28 And { 29 And BaseChild child1; , 30, BaseChild child2 ( get 5 ); 31, return of 0 ; 32 }
The constructor of the parent class can not be inherited, it must be referenced in the sub-class constructor initialization list, otherwise it will call the default constructor of the parent class
The constructor have default parameters:
1 #include <iostream> 2 using namespace std; 3 class Base 4 { 5 public: 6 Base(int val):m_num(val){ 7 cout<<"this is Base(int val)"<<endl; 8 } 9 private: 10 int m_num; 11 }; 12 13 class BaseChild:public Base 14 { 15 public: 16 BaseChild(int val=14):Base(val){ 17 cout<<"this is BaseChild(val)"<<endl; 18 } 19 }; 20 21 int main(int argc,char *argv[]) 22 { 23 BaseChild child1; 24 return 0; 25 }
Note that if a subclass constructor no default parameters will be given because the parent class, subclass, no parameters are not defined constructor; and if the parent class, subclass plus constructor with no arguments will error, because it will produce ambiguity problem, the compiler does not know what the user wants constructor calls
reference:
c ++ constructor initializes the class object
https://blog.csdn.net/weixin_43891901/article/details/89227108
c ++ constructor initializes subclass
https://www.cnblogs.com/clovershell/p/10246629.html
c ++ ambiguity problem