Docsity

Object-Oriented Programming: Drawing and Calculating Areas of Different Shapes, Slides of Object Oriented Programming

Partial preview of the text

Download Object-Oriented Programming: Drawing and Calculating Areas of Different Shapes and more Slides Object Oriented Programming in PDF only on Docsity!

Object-Oriented Programming

(OOP)

Lecture No. 28

Problem Statement

  • Develop a function that can draw different

types of geometric shapes from an array

Shape Hierarchy

class Shape {

…

protected:

char _type;

public:

Shape() { } void draw(){ cout << ā€œShape\nā€; } int calcArea() { return 0; } char getType() { return _type; }

}

… Shape Hierarchy

class Line : public Shape {

…

public:

Line(Point p1, Point p2) {

… } void draw(){ cout << ā€œLine\nā€; }

}

… Shape Hierarchy

class Triangle : public Shape {

…

public:

Triangle(Line l1, Line l2, double angle) { … } void draw(){ cout << ā€œTriangle\nā€; } int calcArea() { … }

}

Drawing a Scene

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;

}

Sample Output

Shape

Shape

Shape

Shape

…

Function drawShapes()

void drawShapes(

Shape* _shape[], int size) { for (int i = 0; i < size; i++) { // Determine object type with

// switch & accordingly call // draw() method }

}

Equivalent If Logic

if ( _shape[i]->getType() == ā€˜L’ )

static_cast<Line*>(_shape[i])->draw();

else if ( _shape[i]->getType() == ā€˜C’ ) static_cast<Circle*>(_shape[i])->draw();

…

Sample Output

Line

Circle

Triangle

Circle

…

…Delocalized Code

  • Consider a function that prints area of

each shape from an input array

Function printArea

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. }

}

…Delocalized Code

  • The above switch logic is same as was in

function drawArray()

  • Further we may need to draw shapes or

calculate area at more than one places in

code

Other Problems

  • Programmer may forget a check
  • May forget to test all the possible cases
  • Hard to maintain