Search code examples
c++polymorphismoperator-overloadingvirtual

How does overloading a Virtual method differ from a Non-Virtual method?


What is the difference between these two:

  • Declaring the base class function virtual and changing the derived class function.
  • Overloading an inherited non-virtual function.

When would you use one over the other?


Solution

  • When you have a Base class method declared as virtual, In order to override it you need to provide an function with exact same signature in Derived class(Co-variant return types are allowed though).

    If your function name is same but the signature in Derived class varies from one in Base class than it is not overidding anymore, It is function Hiding, the derived class method hides the Base class method.

    Function Overloading is never accross classes, You can overload methods inside the same class or free functions but not accross classes. When you attempt to do it accross classes what you eventually get is function hiding.

    To bring the Base class methods in scope of your Derived class you need to add an
    additional using functionName, to your Derived class.

    EDIT:
    As for the Q of when to use virtual over overloading,the answer is:
    If you intend functions of your class to be overridden for runtime polymorphism you should mark them as virtual, and not if you don't intend so.

    Good Read:
    When to mark a function in C++ as a virtual?