C++ Language



Admission Enquiry Form

  

Parameterized Constructor in Inheritance




Use of Parameterized Constructor in Inheritance

Example:

#include<iostream>
using namespace std;
class Base
{
int num;
public:
Base()
{
cout<<"Base default constructor ";
}
Base(int n)
{
num=n;
cout<<"\nBase parameterized cons. "<<num;
}
};
class Derived:public Base
{
public:
Derived(int x)
{
cout<<"\nDerived parameterized cons. "<<x;
}
};
int main()
{
Derived d(500);
return 0;
}


Output:

Base default constructor
Derived parameterized cons. 500
Note: In case of parameterized constructor ,Parameter will be given to derived class constructor first.So, we have to create default constructor in base class to initialize base class first.


Code to call Base Parameterized Constructor First

Example:

#include<iostream>
using namespace std;
class Base
{
int num;
public:
Base(int n)
{
num=n;
cout<<"\nBase parameterized cons. "<<num;
}
};
class Derived : public Base
{
public:
Derived(int x) : Base(x) //Here Base parameterized constructor will called first
{
cout<<"\nDerived parameterized cons. "<<x;
}
};
int main()
{
Derived d(500);
return 0;
}

Output:

Base parameterized cons. 500
Derived parameterized cons. 500