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

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

2011/2012

Uploaded on 11/09/2012

bacha
bacha 🇮🇳

4.3

(41)

213 documents

1 / 31

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Object-Oriented Programming
(OOP)
Lecture No. 28
Docsity.com
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f

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