Page 306 - Computer_Science_F5
P. 306
};
// This code shows a child class Rectangle
class Rectangle : public Shape {
public: Chapter Four: Object oriented programming with C++
FOR ONLINE READING ONLY
// Overriding the draw() method
void draw() override {
cout << “ The drawn rectangle is expected here “ << endl;
}
};
// This function will draw any shape
void drawShape(Shape* shape) {
shape->draw();
}
int main() {
//This will create objects of various shapes
Circle circle;
Rectangle rectangle;
// This shows behaviors for Polymorphism
drawShape(&circle);
drawShape(&rectangle);
return 0;
}
Output:
Figure 4.72: Output of polymorphism program
In the code above, there is a parent the drawShape() function, which accepts
class called Shape, which has a virtual a pointer to the base class Shape.
function named draw().
Polymorphism is achieved through the
Two child classes, Circle and Rectangle, use of virtual functions. The draw()
are created. These classes override the function in the parent class Shape is
draw() method inherited from the Shape declared as virtual, allowing child
classes to override it. The function
class. In the main() function, the concept drawShape() takes a pointer to a Shape
of polymorphism is demonstrated. and calls draw() on it, demonstrating
Different objects of shapes are passed to runtime polymorphism.
297
Student’s Book Form Five
Computer Science Form 5.indd 297 23/07/2024 12:34

