In: Computer Science
C++ Code Required to Show
The constructor of parent class executes before child class
In C++, default constructer can present in all class. From the below example we can see how the constructers are called in inheritance.
Constructers of parent class are always called in the child class constructors. Whenever you create child class object, first the parent class default constructor is executed and then the child class's constructor is executed.
We attributes and functions of parent class are always we can use in the it's child class. So when we create a object of a child class, all of the data menbers and functions of child class must be initialized but the inherited members in child class can only be initialized by the constructor of the parent class because it's deefinition is exist in the parent class. Thus we can say that parent class is called first to initialize all the members and functions of it's inherited class.
You can see it in the below image :
#include <iostream>
using namespace std;
class Parent
{
public:
// default constructor
Parent()
{
cout << "Parent class constructor" << endl;
}
};
class Child : public Parent
{
public:
// default constructor
Child()
{
cout << "Child class constructor" << endl;
}
};
int main()
{
cout << "When we call object of parent class" << endl;
Parent p;
cout << endl;
cout << "When we call object of child class" << endl;
Child c;
}
OUTPUT :
Now for parameterized constructor :
we have to mention that if if want to call parameterized constuctor of parent class from child class as shown in the below code. Parameterised constructor of parent class cannot be called in default constructor of child class, it should be called in the parameterised constructor of child class.
#include <iostream>
using namespace std;
class Parent
{
int x;
public:
// default constructor
Parent()
{
cout << "Parent default constructor" << endl;
}
//parameterized constructor
Parent(int i)
{
cout << "Parent parameterised constructor" << endl;
}
};
class Child : public Parent
{
public:
// default constructor
Child()
{
cout << "Child default constructor" << endl;
}
//parameterized constructor
Child(int j):Parent(j)
{
cout << "Child Parameterized Constructor" << endl;
}
};
int main()
{
cout << "When we call object of parent class" << endl;
Parent p;
cout << endl;
cout << "When we call object of child class" << endl;
Child c;
cout << endl;
cout << "When we call object of child class with parameter" << endl;
Child c1(10);
}
CODE :
OUTPUT :