0

The answer "Calling a non-virtual function will use the function from the same class as the pointer type, regardless of whether the object was actually created as some other derived type. Whereas calling a virtual function will use the function from the original allocated object type, regardless of what kind of pointer you're using." was the best to me in the question link What are the differences between overriding virtual functions and hiding non-virtual functions?

However, I still don't see the benefits of making a function virtual. Why not just make it concrete and override the function when necessary?

1 Answers1

0

All the answers in your link are pretty complicated, since they actually answer more questions than actually asked :-)

I try to make it easier (lets hope for the best):

The concept of a virtual function allows you to guarantee that whatever pointer you use (see the example in the link Parent* p2 or Child* cp) on a class with some inheritance involved, it will always call the "youngest" child's implementation in the inheritance chain.

Example: If you have "child -> parent" and "grandchild -> child -> parent" with exact same function f2() definitions and all virtual, you can now assume that "grandchild::f2" is called in all circumstances. If you omitted the "virtual" keyword in your parent, you would have different functions being called, depending on which pointer you use to access the instance.

So. What is this useful for? Imagine you have a template based collection and want to put children inside the collection that is defined as parent-type collection list<Parent*>. If you now call a function on an element you fetch from the list, you can expect the child's function (definition) to be called! If you omit the "virtual" keyword in the f2() definition, the parents function is going to be called, which might be unexpected/undesired in most cases.

Any better? :-)

Peter Branforn
  • 1,679
  • 3
  • 17
  • 29