Unexpected Inheritance Output | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
0

Unexpected Inheritance Output

For some reason, this code outputs the constructor and destructor multiple times. Does anybody know why? Is it once for each derived class? #include <iostream> using namespace std; class Mother { public: Mother() { cout << "Mother ctor" << endl; }; void sayHi() { cout << "Hi"; } void sayHello() { cout << "Hello"; } ~Mother() { cout << "Mother dtor" << endl; } }; class Daughter: public Mother { public: Daughter() {}; }; class Son: public Mother { public: Son() {}; }; int main() { Mother m; Daughter d; Son s; d.sayHi(); cout << "\n"; s.sayHello(); cout << "\n"; }

21st May 2018, 4:51 AM
Michelle
Michelle - avatar
4 ответов
+ 17
I added some more output to your code to help illustrate what is occurring here. You will see that, yes, for each instance of a derived class the base classes constructor is called/executed https://code.sololearn.com/c31g2he7jN7Q/?ref=app
21st May 2018, 5:24 AM
jay
jay - avatar
+ 1
Thanks Jay!
21st May 2018, 5:39 AM
Michelle
Michelle - avatar
+ 1
The code is great showing that a set of the outputs are due to creation/constructor for the class.
21st May 2018, 1:12 PM
Michelle
Michelle - avatar
0
answe is ~mother and mother.
14th Jan 2020, 1:25 PM
Imanuel Wicaksono
Imanuel Wicaksono - avatar