Professional Documents
Culture Documents
polymorphism
CIT743
CIT743
CIT743
Example:
Design and implement a program that deals with two types of
polygons, rectangle and triangle. User is allowed to specify the
two dimensions width and height of each polygon then
calculate and display area of each.
Solution
Inheritance can be applied as usual;
# include <iostream>
using namespace std;
class Polygon {
protected:
float width, height, area;
public:
void setDimensions (float w, float h) {
width=w;
height=h;
}
CIT743
CIT743
void calculateArea(){
area=width*height/2; }
};
int main () {
Rectangle rect;
Triangle tri;
float w,h;
cout<< Specify width and height of Rectangle:;
cin>>w; cin>> h;
rect.setDimensions(w,h);
cout<< Specify width and height of Triangle:;
cin>>w; cin>> h;
tri.setDimensions(w,h);
rect.calculateArea();
tri.calculateArea();
CIT743