practical 5:Inheritance
MULTILEVEL INHERITANCE:
#include<iostream>
#include<conio.h>
using namespace std;
class rectangle
{
protected:
float length;
float width;
public:
void setlength()
{
cout<<"your length: "<<endl;
cin>>length;
cout<<"your width: "<<endl;
cin>> width;
}
};
class area : public rectangle
{
public:
float calc()
{
return(length*width);
}
};
class peri: public area
{
public:
float calc1()
{
return (2*(length*width));
}
};
int main()
{
peri a;
cout<<"enter the data for first rectangle to find the area: "<<endl;
a.setlength();
cout<<"area is : "<< a.calc() <<"sq/m"<<endl;
cout<<"enter the data for rectangle to find the perimeter: "<<endl;
a.setlength();
cout<<"perimeter is: "<< a.calc1() << "m" <<endl;
getch();
return(0);
}
MULTIPLE INHERITANCE :
#include<iostream>
#include<conio.h>
using namespace std;
class student
{
protected:
int no,m1,m2;
public:
student()
{
cout<<"enter the roll no. "<<endl;
cin>>no;
cout<<"enter the marks of two subject "<<endl;
cin>>m1>>m2;
}
};
class sports
{
protected:
int spo;
public:
sports()
{
cout<<"enter the sports marks: "<<endl;
cin>>spo;
}
};
class statement : public student ,public sports
{
float total,avg;
public:
void display()
{
total=(m1+m2+spo);
avg=total/3;
cout<<"total marks is : "<<total<<endl;
cout<<"average is : "<<avg<<endl;
}
};
int main()
{
statement obj;
obj.display();
getch();
return(0);
}
Hierarchical inheritance:
#include<iostream>
#include<conio.h>
using namespace std;
class A //base class
{
protected:
int a;
public:
void getnumber()
{
cout<<"enter the number :...."<<endl;
cin>>a;
}
};
class B:public A
{
public:
int squr()
{
cout<<"square is : "<<(a*a)<<endl;
}
};
class C :public A
{
public:
void qube()
{
cout<<"qube is : "<<(a*a*a)<<endl;;
}
};
int main()
{
B b1;
b1.getnumber();
b1.squr();
C c1 ;
c1.getnumber();
c1.qube();
getch();
return(0);
}
Hybrid inheritance:
#include<iostream>
#include<conio.h>
using namespace std;
class arithmetic
{
protected:
int num1, num2;
public:
void getdata()
{
cout<<"For Addition:";
cout<<"\nEnter the first number: ";
cin>>num1;
cout<<"\nEnter the second number: ";
cin>>num2;
}
};
class plusl:public arithmetic
{
protected:
int sum;
public:
void add()
{
sum=num1+num2;
}
};
class minusl
{
protected:
int n1,n2,diff;
public:
void sub()
{
cout<<"\nFor Subtraction:";
cout<<"\nEnter the first number: ";
cin>>n1;
cout<<"\nEnter the second number: ";
cin>>n2;
diff=n1-n2;
}
};
class result:public plusl, public minusl
{
public:
void display()
{
cout<<"\nSum of "<<num1<<" and "<<num2<<"= "<<sum;
cout<<"\nDifference of "<<n1<<" and "<<n2<<"= "<<diff;
}
};
int main()
{
result z;
z.getdata();
z.add();
z.sub();
z.display();
getch();
return(0);
}