12th OOP Lecture 21-02-2023
12th OOP Lecture 21-02-2023
(OOP)
Lecture
by
Muhammad Majid
Cell: 03006956702
Email: [email protected]
Problem Statement
Shape
draw
calcArea
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
}
}
Required Switch Logic
switch ( _shape[i]->getType() )
{
case ‘L’:
static_cast<Line*>(_shape[i])->draw();
break;
case ‘C’: static_cast<Circle*>(_shape[i])
->draw();
break;
…
}
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
…
Problems with Switch
Statement
…Delocalized Code
• Hard to maintain
Solution?
class Shape {
…
virtual void draw();
}
Shape Hierarchy
Shape
draw
calcArea
Line
Circle
Triangle
Circle
…
Function printArea
void printArea(Shape* _shape[],
int size) {
for (int i = 0; i < size; i++) {
// Print shape name
cout<< _shape[i]
->calcArea();
cout << endl;
}
}
Static vs Dynamic Binding