Reputation: 22926
class Shape
{
void draw ();
void move ();
void resize ();
}
class Square : public Shape
{
// Re implement the draw function so that it draws a Square.
void draw ();
}
void callDraw (Shape& arg)
{
arg.draw ();
}
int main ()
{
callDraw (Square& arg);
}
(P.S. I know that we need to use the keyword virtual
here to make this actually work.)
How does this actually help us in preventing us from writing more code?
In that function too we are calling the draw function like arg.draw()
. So, how much time will it take for us write that call in the main function?
What point am I missing here?
Upvotes: 0
Views: 56
Reputation: 1161
It doesn't result in less code; in this case it lets you keep square logic separate from triangle logic and circle logic; rather than having
void draw() {
if (isSquare) {
drawSquare();
} else if (isTriangle) {
drawTriangle();
} else if (isCircle) {
drawCircle();
}
}
You could use a switch-case instead of if-else-ifs but no matter what you do, it's going to be ugly.
With the virtual methods, adding or removing a shape doesn't require going into your Shape.draw() function to modify logic (if you've got several methods it becomes even more relevant); you simply add or remove the shape's class and the rest is taken care of.
Upvotes: 2