简体   繁体   中英

Parametrized constructor calling in main in Inheritance C++

Suppose I have two classes Mother and Daughter, where Daughter inherits publicly from Mother. Now if I want to call the parametrized constructor of Daughter, how will it go about?

class Mother
{ int age; 
  public: 
   Mother(int a) {
   age = a; 
   court << "Mother Paramterized constructor called!\n " ; 
   }
};
class Daughter: public Mother 
{
   int height; 
   public: 
  Daughter(int h): Mother(x) {
   height = h; 
   court << "Daughter parametrized constructor!\n"; 
   }
};

The class definitions will be as above (as far as I know) but how will the call to Daughter parameterized constructor go about?

You can call the parameterized constructors with

class Mother {
  int age; 
public: 
  Mother(int a) : age(a) {
    cout << "Mother Paramterized constructor called!\n " ; 
  }
};

class Daughter: public Mother {
  int height; 
public: 
  Daughter(int a, int h): Mother(a), height(h) {
    cout << "Daughter parametrized constructor!\n"; 
  }
};


int main() {
  Daughter d(10, 150);
}

Output:

Mother Paramterized constructor called!
 Daughter parametrized constructor!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM