0

From the code given below, the output should be 12(because constructor never inherit ) but it is 112 . How? Someone can explain.

#include <iostream> using namespace std; class a {public: int x; a() {x=1; cout<<x; } }; class b:public a {public: int y; b() {y=2; cout<<y; } }; int main() { a ob1; b ob2; return 0; } //output //112

21st Dec 2016, 4:09 AM
blumen
blumen - avatar
5 Answers
+ 3
Because the base class' constructor is called by the child when it's created.
21st Dec 2016, 5:46 AM
Karl T.
Karl T. - avatar
+ 3
Inheritance has to do with the fact that methods can be used by the derived classes. Not that they are called automatically...constructors that have no parameters are called automatically when an object is created.
21st Dec 2016, 6:05 AM
Karl T.
Karl T. - avatar
+ 2
Constructor can't inherit in the meaning that when you create custom constructor, it don't override it's parent's constructor ( in the base class )... So, it's why the constructor of a in your code is called 2 times : one first for the creation of the ob1 instance, and a second one, just before the creation of ob2's instance and it's call to b's constructor.
21st Dec 2016, 7:57 AM
visph
visph - avatar
+ 1
During the first instantiation --> a ob1; base class is called a() --> output = 1 During the second instantiation --> b ob2; child class inherits the property of base class . so b() calls the parent class constructor a() before it (child class constructor b() ) gets executed. b() --> output 12 Overall Output -> 112
21st Dec 2016, 10:54 AM
Bhalaji V M
Bhalaji V M - avatar
0
that i know but how because constructor can't inherit
21st Dec 2016, 5:56 AM
blumen
blumen - avatar