Example:3
//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 n1,int n2):hello(n1,n2) { c=n1; d=n2; } void show() { cout<<"c = "<<c<<" d = "<<d<<endl; } }; class sample:public hi { private: int e,f; public: sample(int n1,int n2):hi(n1,n2) { e=n1; f=n2; } void show() { cout<<"e = "<<e<<" f = "<<f<<endl; } }; int main() { int a1,a2; cout<<"Enter 2 nos "; cin>>a1>>a2; sample h(a1,a2); h.show(); h.hi::show(); h.hello::show(); return(0); }
Output:
Enter 2 nos 100
200
e = 100 f = 200
c = 100 d = 200
a = 100 b = 200
Example:4
//to initilize the data elements of base class //using constructor function of derived calss //multiple 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 n1,int n2):hello(n1,n2) { c=n1; d=n2; } void show() { cout<<"c = "<<c<<" d = "<<d<<endl; } }; class sample:public hello { private: int e,f; public: sample(int n1,int n2):hello(n1,n2) { e=n1; f=n2; } void show() { cout<<"e = "<<e<<" f = "<<f<<endl; } }; int main() { hi h1(100,200); sample s1(1000,2000); h1.show(); s1.show(); return(0); }
Output:
c = 100 d = 200
e = 1000 f = 2000
Example:5
//Exam_1.cpp //exam_1.cpp #include<iostream> #include<conio.h> #include<string.h> using namespace std; class student { private: int roll; char name[20]; public: student() { roll=0; name[0]='\0'; } student(int r,char *n) { roll=r; strcpy(name,n); } void show1() { cout<<"roll "<<roll<<" name "<<name<<endl; } }; class exam:public student { private: float m1,m2,m3; public: exam() { m1=0;m2=0;m3=0; } exam(int tr,char *tn,float tm1,float tm2,float tm3): student(tr,tn) { m1=tm1; m2=tm2; m3=tm3; } void show2() { cout<<"m1 "<<m1<<" m2 "<<m2<<" m3 "<<m3<<endl; } }; class result:public exam { private: float total,per; public: result() { total=0;per=0; } result(int tr,char *tn,float tm1,float tm2,float tm3): exam(tr,tn,tm1,tm2,tm3) { total=tm1+tm2+tm3; per=total/3; } void show3() { cout<<"total "<<total<<" per "<<per<<endl; } }; int main() { result r(101,"amit",98,99,97); r.show1(); r.show2(); r.show3(); getch(); return(0); }
Output:
roll 101 name amit
m1 98 m2 99 m3 97
total 294 per 98