K .J.Somaiya Polytechnic, Mumbai-77: Batch No: CO2
K .J.Somaiya Polytechnic, Mumbai-77: Batch No: CO2
Experiment No: 19
Experiment No.19
Theory:
Types of Inheritance
In C++, we have 5 different types of Inheritance. Namely,
1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
5. Hybrid Inheritance (also known as Virtual Inheritance)
1.Single Inheritance:
Single Inheritance: In single inheritance, a class is allowed to inherit from only one class.
i.e. one sub class is inherited by one base class only.
3.Hierarchical Inheritance:
In this type of inheritance, more than one sub class is inherited from a single base class. i.e.
more than one derived class is created from a single base class.
4.Multilevel Inheritance:
In this type of inheritance, a derived class is created from another derived class.
1. Single Inheritance:
Input:
#include<iostream.h>
#include<conio.h>
class A
private:
public:
void get_a()
cout<<"Enter a ";
cin>>a;
void put_a()
cout<<a;
};
class B:public A
int b;
public:
void get_b()
cout<<"Enter b ";
cin>>b;
void put_b()
cout<<b;
int main()
clrscr();
A a1;
a1.get_a();
a1.put_a();
B b1;
b1.get_b();
b1.get_a();
b1.put_a();
b1.put_b();
getch();
return 0;
Output:
#include<iostream.h>
#include<conio.h>
class M
{
protected:
int m;
public:
void get_m(int x)
{m=x;}
};
class N
{
protected:
int n;
public:
void get_n(int y)
{n=y;}
};
class P:public M,public N
{
public:
void display()
{
cout<<"m ="<<m<<endl;
cout<<"n ="<<n<<endl;
cout<<"m * n ="<<m*n;
}
};
void main()
{
clrscr();
P p1;
p1.get_m(10);
p1.get_n(20);
p1.display();
getch();
}
3. Hierarchical Inheritance:
Input:
#include<iostream.h>
#include<conio.h>
class father
{
int age;
char name[20];
public:
void get()
{
cout<<"Enter father's name:";
cin>>name;
cout<<"Enter father's age:";
cin>>age;
}
void show()
{
cout<<"\n Father's name is "<<name;
cout<<"\n Father's age is "<<age;
}
};
class son:public father
{
int age;
Output:
4. Multilevel Inheritance:
Input:
#include<iostream.h>
#include<conio.h>
class vehicle
public:
vehicle()
cout<<"This is a vehicle"<<endl;
public:
fourwheeler()
};
class car:publicfourwheeler
public:
car()
};
int main()
clrscr();
car obj;
getch();
return 0;
Output:
#include<iostream.h>
#include<conio.h>
class arithmetic
{
protected:
int num1,num2;
public:
void getdata()
{
cout<<"For addition:";
cout<<"\n Enter the first number:";
cin>>num1;
cout<<"\n Enter the second number:";
cin>>num2;
}
};
class plus:public arithmetic
{
protected:
int sum;
public:
void add()
{
sum=num1+num2;
}
};
class minus
{
protected:
Output: