Exercise -4 (Inheritance):
a) Write C++ Programs and incorporating various forms of Inheritance
i) Single Inheritance
ii) Hierarchical Inheritance
iii) Multiple Inheritances
iv) Multi-level inheritance
v) Hybrid inheritance
b) Also illustrate the order of execution of constructors and destructors in inheritance
i) Single Inheritance
#include<iostream>
using namespace std;
class AddData //Base Class
{
protected:
int num1, num2;
public:
void accept()
{
cout<<"\n Enter First Number : ";
cin>>num1;
cout<<"\n Enter Second Number : ";
cin>>num2;
}
};
class Addition: public AddData //Class Addition – Derived Class
{
int sum;
public:
void add()
{
sum = num1 + num2;
}
void display()
{
cout<<"\n Addition of Two Numbers : "<<sum;
}
};
int main()
{
Addition a;
a.accept();
a.add();
a.display();
return 0;
}
Output:
Multi-level inheritance :
#include<iostream>using namespace std;
class AddData //Base Class
{
protected:
int subjects[3], i;
public:
void accept_details()
{
cout<<"\n Enter Marks for Three Subjects ";
cout<<"\n ------------------------------- \n";
cout<<"\n English : ";
cin>>subjects[0];
cout<<"\n Maths : ";
cin>>subjects[1];
cout<<"\n History : ";
cin>>subjects[2];
}
};
//Class Total – Derived Class. Derived from class AddData and Base class of class Percentage
class Total : public AddData
{
protected:
int total;
public:
void total_of_three_subjects()
{
total = subjects[0] + subjects[1] + subjects[2];
}
};
class Percentage : public Total //Class Percentage – Derived Class. Derived from class Total
{
private:
float per;
public:
void calculate_percentage()
{
per=total/3;
}
void show_result()
{
cout<<"\n ------------------------------- \n";
cout<<"\n Percentage of a Student : "<<per;
}
};
int main()
{
Percentage p;
p.accept_details();
p.total_of_three_subjects();
p.calculate_percentage();
p.show_result();
return 0;
}
Output:
The square value is:: 100
The cube value is::8000
Multiple Inheritance in C++
Hybrid Inheritance in C++
Enter a and b value: 5 10
Enter c value: 15
Enter d value: 20
Addition is :50
No comments