Can someone explain the benefits of polymorphism?

前端 未结 10 447
难免孤独
难免孤独 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:26

    Both your examples do the same thing but in different ways.
    The first example calls function() by using Static binding while the second calls it using Dynamic Binding.

    In first case the compiler precisely knows which function to call at compilation time itself, while in second case the decision as to which function should be called is made at run-time depending on the type of object which is pointed by the Base class pointer.

    What is the advantage?
    The advantage is more generic and loosely coupled code.

    Imagine a class hierarchy as follows:

    enter image description here

    The calling code which uses these classes, will be like:

    Shape *basep[] = { &line_obj, &tri_obj,
                       &rect_obj, &cir_obj};
    for (i = 0; i < NO_PICTURES; i++)
        basep[i] -> Draw ();
    

    Where, line_obj, tri_obj etc are objects of the concrete Shape classes Line, Triangle and so on, and they are stored in a array of pointers of the type of more generalized base class Shape.

    This gives the additional flexibility and loose coupling that if you need to add another concrete shape class say Rhombus, the calling code does not have to change much, because it refers to all concrete shapes with a pointer to Base class Shape. You only have to make the Base class pointer point to the new concrete class.

    At the sametime the calling code can call appropriate methods of those classes because the Draw() method would be virtual in these classes and the method to call will be decided at run-time depending on what object the base class pointer points to.

    The above is an good example of applying Open Closed Principle of the famous SOLID design principles.

提交回复
热议问题