Inheritance in C++

Inheritance in C++


Single Inheritance in C++:


  1. #include<iostream>  
  2. using namespace std;  
  3.   
  4. class Shape{  
  5. private:  
  6.     int l,h;  
  7. public:  
  8.     void setDetails(int a,int b);  
  9.     int getDetails(){  
  10.         return l*h;  
  11.     }  
  12. };  
  13. void Shape::setDetails(int a,int b){  
  14.     l=a;  
  15.     h=b;  
  16. }  
  17.   
  18. class Rectangle:public Shape{  
  19. public:  
  20.     void showArea(){  
  21.         cout<<"Rectangle Area: "<<getDetails()<<endl;  
  22.     }  
  23. };  
  24.   
  25. int main()  
  26. {  
  27.     Rectangle aRectangle;  
  28.     aRectangle.setDetails(3,6);  
  29.     aRectangle.showArea();  
  30.     return 0;  
  31. }  

Multiple Inheritance in C++:


  1. #include<iostream>  
  2. using namespace std;  
  3.   
  4. class Area{  
  5. private:  
  6.     int length;  
  7.     int width;  
  8. public:  
  9.     void setArea(int x,int y){  
  10.     length=x;  
  11.     width=y;  
  12.     }  
  13.     int getArea(){  
  14.         return length*width;  
  15.     }  
  16. };  
  17.   
  18. class Height{  
  19. private:  
  20.     int h;  
  21. public:  
  22.     void setHeight(int x){  
  23.         h=x;  
  24.     }  
  25.     int getHeight(){  
  26.         return h;  
  27.     }  
  28. };  
  29.   
  30. class Volume:public Area,public Height{  
  31. public:  
  32.     void getVolume(){  
  33.         cout<<"Volume: "<<getArea()*getHeight()<<endl;  
  34.     }  
  35. };  
  36.   
  37. int main()  
  38. {  
  39.     Volume vol;  
  40.     vol.setArea(4,3);  
  41.     vol.setHeight(7);  
  42.     vol.getVolume();  
  43.     return 0;  
  44. }  
Share:

0 Comments:

Post a Comment