Can someone explain the benefits of polymorphism?

前端 未结 10 448
难免孤独
难免孤独 2021-02-01 10:41

So I understand pretty much how it works, but I just can\'t grasp what makes it useful. You still have to define all the separate functions, you still have to create an instanc

10条回答
  •  执笔经年
    2021-02-01 11:31

    There are countless examples of nice uses of polymorphism. Consider as an example a class that represents GUI widgets. The most base classs would have something like:

    class BaseWidget
    {
    ...
    virtual void draw() = 0;
    ...
    };
    

    That is a pure virtual function. It means that ALL the class that inherit the Base will need to implement it. And ofcourse all widgets in a GUI need to draw themselves, right? So that's why you would need a base class with all of the functions that are common for all GUI widgets to be defined as pure virtuals because then in any child you will do like that:

    class ChildWidget
    {
     ...
      void draw()
      {
         //draw this widget using the knowledge provided by this child class
      }
    };
    
    
    class ChildWidget2
    {
     ...
      void draw()
      {
         //draw this widget using the knowledge provided by this child class
      }
    };
    

    Then in your code you need not care about checking what kind of widget it is that you are drawing. The responsibility of knowing how to draw itself lies with the widget (the object) and not with you. So you can do something like that in your main loop:

    for(int i = 0; i < numberOfWidgets; i++)
    {
        widgetsArray[i].draw();
    }
    

    And the above would draw all the widgets no matter if they are of ChildWidget1, ChildWidget2, TextBox, Button type.

    Hope that it helps to understand the benefits of polymorphism a bit.

提交回复
热议问题