Override and overload in C++

后端 未结 7 1498
生来不讨喜
生来不讨喜 2020-12-04 05:56

Yes, I do understand the difference between them. What I want to know is: why OVERRIDE a method? What is the good in doing it? In case of overload: the only advantage is you

7条回答
  •  醉酒成梦
    2020-12-04 06:17

    Override is useful when you inherit from a base class and wish to extend or modify its functionality. Even when the object is cast as the base class, it calls your overridden function, not the base one.

    Overloading is not necessary, but it sure makes life easier or more readable sometimes. Arguably it can make it worse, but that's when it should not be used. For example, you can have two functions that perform the same operation, but act on different kinds of things. For example Divide(float, float) should be different from Divide(int, int), but they're basically the same operation. Wouldn't you rather remember one method name, "Divide", than have to remember "DivideFloat", "DivideInt", "DivideIntByFloat", and so on?

提交回复
热议问题