Programming with Passion

Make the best out of everything.

Saturday, 26 March 2016

Source Code to Implement Inheritance in C++ Programming

Source Code to Implement Inheritance in C++ Programming

This example calculates the area and perimeter a rectangle using the concept of inheritance.

/* C++ Program to calculate the area and perimeter of rectangles using concept of inheritance. */

#include <iostream>
using namespace std;
class Rectangle
{
    protected:
       float length, breadth;
    public:
        Rectangle(): length(0.0), breadth(0.0)
        {
            cout<<"Enter length: ";
            cin>>length;
            cout<<"Enter breadth: ";
            cin>>breadth;
        }

};

/* Area class is derived from base class Rectangle. */
class Area : public Rectangle   
{
    public:
       float calc()
         {
             return length*breadth;
         }

};

/* Perimeter class is derived from base class Rectangle. */
class Perimeter : public Rectangle
{
    public:
       float calc()
         {
             return 2*(length+breadth);
         }
};

int main()
{
     cout<<"Enter data for first rectangle to find area.\n";
     Area a;
     cout<<"Area = "<<a.calc()<<" square meter\n\n";

     cout<<"Enter data for second rectangle to find perimeter.\n";
     Perimeter p;
     cout<<"\nPerimeter = "<<p.calc()<<" meter";
     return 0;
}
Output
Enter data for first rectangle to find area.
Enter length: 5
Enter breadth: 4
Area = 20 square meter

Enter data for second rectangle to find perimeter.
Enter length: 3
Enter breadth: 2
Area = 10 meter
Explanation of Program
In this program, classes Area and Perimeter are derived from class Rectangle. Thus, the object of derived class can access the public members of Rectangle. In this program, when objects of class Area and Perimeter are created, constructor in base class is automatically called. If there was public member function in base class then, those functions also would have been accessible for objects a and p.

No comments:

Post a Comment