























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
The code for a shape hierarchy in c++ where different types of geometric shapes, including line, circle, and triangle, can be drawn and their areas calculated. The use of virtual functions and polymorphism to automatically select the message target at run-time, avoiding the need for switch statements.
Typology: Slides
1 / 31
This page cannot be seen from the preview
Don't miss anything!
























class Shape {
…
protected:
char _type;
public:
Shape() { } void draw(){ cout << “Shape\n”; } int calcArea() { return 0; } char getType() { return _type; }
}
class Line : public Shape {
…
public:
Line(Point p1, Point p2) {
… } void draw(){ cout << “Line\n”; }
}
class Triangle : public Shape {
…
public:
Triangle(Line l1, Line l2, double angle) { … } void draw(){ cout << “Triangle\n”; } int calcArea() { … }
}
int main() {
Shape* _shape[ 10 ]; Point p1(0, 0), p2(10, 10); shape[1] = new Line(p1, p2); shape[2] = new Circle(p1, 15); … void drawShapes( shape, 10 ); return 0;
}
Shape
Shape
Shape
Shape
…
void drawShapes(
Shape* _shape[], int size) { for (int i = 0; i < size; i++) { // Determine object type with
// switch & accordingly call // draw() method }
}
if ( _shape[i]->getType() == ‘L’ )
static_cast<Line*>(_shape[i])->draw();
else if ( _shape[i]->getType() == ‘C’ ) static_cast<Circle*>(_shape[i])->draw();
…
Line
Circle
Triangle
Circle
…
void printArea(
Shape* _shape[], int size) { for (int i = 0; i < size; i++) { // Print shape name. // Determine object type with // switch & accordingly call // calcArea() method. }
}