To initialize base class data elements using derived class constructors
Or
To invoke base class constructors using derived class constructors
Or
To pass arguments from derived class constructor to base class constructor.
Example:1
//to initilize the data elements of base class //using constructor of drived class //single inheritance #include<iostream> using namespace std; class hello { private: int a,b; public: hello(int n1,int n2) { a=n1; b=n2; } void show() { cout<<"a = "<<a<<" b = "<<b<<endl; } }; class hi:public hello { private: int c,d; public: hi(int a1,int a2,int a3,int a4):hello(a1,a2) { c=a3; d=a4; } void disp() { cout<<"c = "<<c<<" d = "<<d<<endl; } }; int main() { hi h(10,20,30,40); h.show(); h.disp(); return(0); }
Output:
a = 10 b = 20
c = 30 d = 40
Example:2
//to initilize the data elements of base class //using constructor function of derived calss //multilevel imheritance #include<iostream> using namespace std; class hello { private: int a,b; public: hello(int n1,int n2) { a=n1; b=n2; } void show() { cout<<"a = "<<a<<" b = "<<b<<endl; } }; class hi:public hello { private: int c,d; public: hi(int a1,int a2,int a3,int a4):hello(a1,a2) { c=a3; d=a4; } void disp() { cout<<"c = "<<c<<" d = "<<d<<endl; } }; class sample:public hi { private: int e,f; public: sample(int x1,int x2,int x3,int x4,int x5,int x6):hi(x1,x2,x3,x4) { e=x5; f=x6; } void output() { cout<<"e = "<<e<<" f = "<<f<<endl; } }; int main() { sample h(10,20,30,40,50,60); h.show(); h.disp(); h.output(); return(0); }
Output:
a = 10 b = 20
c = 30 d = 40
e = 50 f = 60