0

Confusion between member initializer list and invoking parent class constructor upon making daughter class constructor

#include <iostream> using namespace std; class animal { public: animal(string n, int a) { name = n; age = a; } string name; int age; }; class dog : public animal { public: dog(string n, int a) : animal(n,a), name(n), age(a) { } void speak() { cout << "woof" << endl; } ~dog() { cout << "dog destructor" << endl; } string name; int age; }; int main() { dog tommy("tommy", 10); cout << tommy.name << endl << tommy.age << endl; return 0; } In the daughter constructor line I have to invoke the parent constructor too as otherwise it raises error... So my question is that if I use member initializer list then how would I write it...The way I wrote above by just combining both of them is not working...

10th Oct 2018, 10:57 AM
Rashim Narayan Tiku
Rashim Narayan Tiku - avatar
4 Answers
+ 7
You are doubling up on info, you don't need to store age and name in dog, as the parent class has this info. So you could write like so: (if all animals share the attributes age and name that is) class dog : public animal { public: dog(string n, int a) : animal(n,a) { } };
10th Oct 2018, 11:13 AM
jay
jay - avatar
+ 3
Rashim Narayan Tiku like you already have, like so: class dog : public animal { public: dog(string n, int a ,string c) : animal(n,a), colour(c) { } string colour; }; https://code.sololearn.com/csKd68E93AxZ/?ref=app
10th Oct 2018, 11:29 AM
jay
jay - avatar
+ 2
If you create a constructor for a class that get some parameters and, that class, dont create a constructor that DONT get parameters, then your subclass have to call right base constructor for correctly init it because compiler can only init base class if it have a constructor that dont get parameter or a default constructor (created by compiler when you dont define a constructor). In your case, then, you have to call the animal constructor because its the ONLY way to init an animal instance. Futhermore your doubt derive from fact that maybe you have not understanded inheritance. In your dog class, you declare again name and age attribute when its not necessary because it INHERITH they from base class (animal), then your dog class would be: class dog : public animal { public: dog(string n, int a) : animal(n,a) { } void speak() { cout << "woof" << endl; } ~dog() { cout << "dog destructor" << endl; } }; Note that in my example, i dont declared again name and age but you can ALWAYS access to they because they are INERITHED from base class animal
10th Oct 2018, 11:24 AM
KrOW
KrOW - avatar
+ 1
jay that's right but what if I NEEDED to use both member initializer list and parent constructor at the same time...how would I write it?
10th Oct 2018, 11:21 AM
Rashim Narayan Tiku
Rashim Narayan Tiku - avatar