c++ - Treating derived class as base class - how does it help us to prevent writing more code? -


class shape {     void draw ();     void move ();     void resize (); }  class square : public shape {     // re implement draw function draws square.     void draw (); }  void calldraw (shape& arg)  {     arg.draw (); }  int main () {     calldraw (square& arg); } 

(p.s. know need use keyword virtual here make work.) how in preventing writing more code?

in function calling draw function arg.draw(). so, how time take write call in main function?

what point missing here?

it doesn't result in less code; in case lets keep square logic separate triangle logic , circle logic; rather having

void draw() {     if (issquare) {       drawsquare();     } else if (istriangle) {       drawtriangle();     } else if (iscircle) {       drawcircle();     } } 

you use switch-case instead of if-else-ifs no matter do, it's going ugly.

with virtual methods, adding or removing shape doesn't require going shape.draw() function modify logic (if you've got several methods becomes more relevant); add or remove shape's class , rest taken care of.


Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

datatable - Matlab struct computations -