This program demonstrates the use of inheritance in C++ through the creation of a base class Shape and two derived classes Rectangle and Triangle. The Shape class has two public data members a and b and a member function get_data() to set the values of a and b.
The Rectangle class is a derived class of Shape and has a member function rect_area() that calculates the area of a rectangle using the formula area = length x breadth. The Triangle class is also a derived class of Shape and has a member function triangle_area() that calculates the area of a triangle using the formula area = 0.5 x base x height.
In the main() function, objects of Rectangle and Triangle classes are created. The user is asked to input the length and breadth for the Rectangle object and the base and height for the Triangle object. The get_data() function of the base class is called to set the values of a and b for both objects. The rect_area() and triangle_area() functions are then called to calculate the respective areas and the results are displayed on the console.
#include<iostream> using namespace std; class Shape { public: int a; int b; void get_data(int n,int m) { a=n; b=m; } }; class Rectangle : public Shape { public: int rect_area() { int result = a*b; return result; } }; class Triangle : public Shape { public: int triangle_area() { float result = 0.5*a*b; return result; } }; int main() { Rectangle r; Triangle t; int length,breadth,base,height; std::cout<<"Enter the length and breadth of a rectangle: "<<std::endl; cin>>length>>breadth; r.get_data(length,breadth); int m = r.rect_area(); std::cout<<"Area of the rectangle is : "<<m<<std::endl; std::cout<<"Enter the base and height of the triangle: "<<std::endl; cin>>base>>height; t.get_data(base,height); float n = t.triangle_area(); std::cout<<"Area of the triangle is : "<<n<<std::endl; return 0; }To download raw file Click Here
Enter the length and breadth of a rectangle: 20 30 Area of the rectangle is : 600 Enter the base and height of the triangle:
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions