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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
virtualover 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?