What does the keyword virtual do when overriding a method? I’m not using it and everything works fine.
Does every compiler behave the same in this regard?
Should I use it or not?
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.
You cannot override a member function without it.
You can only hide one.
Derived::foodoes not overrideBase::foo; it simply hides it because it has the same name, such that the following:invokes
Derived::foo.virtualenables polymorphism such that you actually override functions:This invokes
Derived::foo, because this now overridesBase::foo— your object is polymorphic.(You also have to use references or pointers for this, due to the slicing problem.)
Derived::foodoesn’t need to repeat thevirtualkeyword becauseBase::foohas already used it. This is guaranteed by the standard, and you can rely on it. However, some think it best to keep that in for clarity.