b22cs028 Rakesh Assignment-1
b22cs028 Rakesh Assignment-1
(B22CS028)
Q1.Create a base class called shape. Use this class to store two double type values that could
be used to compute the area of figures. Derive two specific classes called triangle and rectangle
from the base shape. Add to the base class, a member function get_data() to initialize base class
data members and another member function display_area() to compute and display the area of
figures. Make display_area() as a virtual function and redefine this function in the derived classes
to suit their requirements.
Using these three classes, design a program that will accept dimensions of a triangle or a
rectangle interactively, and display the area.
Remember the two values given as input will be treated as lengths of two sides in the case of
rectangles, and as base and height in the case of triangles.
Input:
#include<iostream>
using namespace std;
class shape{
public:
double value_1;
double value_2;
void get_data(){
cout<<"\nEnter the parameters:\n";
cin>>value_1;
cin>>value_2;
}
virtual void display_area(){
double area=value_1*value_2;
cout<<"the area of the shape is: "<<area;
}
};
int main(){
triangle t1;
t1.display_area();
rectangle r1;
r1.display_area();
return 0;
Output:
Q2.Extend the above program to display the area of circles. This requires addition of a new
derived class 'circle' that computes the area of a circle. Remember, for a circle we need only one
value, its radius, but the the get_data() function in the base class requires two values to be
passed.
Input:
#include <iostream>
#include <cmath>
using namespace std;
class Shape {
protected:
double dimension1;
double dimension2;
public:
Shape() : dimension1(0.0), dimension2(0.0) {}
int main() {
char shape_type;
cout << "Enter shape type (1 for triangle, 2 for rectangle, 3 for circle): ";
cin >> shape_type;
Shape *shape;
switch (shape_type) {
case '1':
shape = new Triangle();
break;
case '2':
shape = new Rectangle();
break;
case '3':
shape = new Circle();
break;
default:
cout << "Invalid shape type." << endl;
return 1;
}
shape->get_data();
shape->display_area();
delete shape;
return 0;
}
Output:
Q3.Run the above program with following modifications:
(a) Remove the definition of display_area() from one of the derived classes.
(b) In addition to the above change, declare the display_area() as virtual in the base class shape.
Input:
#include <iostream>
#include <cmath>
using namespace std;
class Shape {
protected:
double dimension1;
double dimension2;
public:
Shape() : dimension1(0.0), dimension2(0.0) {}
int main() {
char shape_type;
cout << "Enter shape type (1 for triangle, 2 for rectangle, 3 for circle): ";
cin >> shape_type;
Shape *shape;
switch (shape_type) {
case '1':
shape = new Triangle();
break;
case '2':
shape = new Rectangle();
break;
case '3':
shape = new Circle();
break;
default:
cout << "Invalid shape type." << endl;
return 1;
}
shape->get_data();
shape->display_area();
delete shape;
return 0;
}
Output: