I understand that it provides a default implementation that the derived classes can override. But is that the exact purpose?
+9
A:
No, this is not their exact purpose. Virtual functions are means of achieving type polymorphism in an Object-Oriented language.
Anton Gogolev
2009-08-24 12:58:12
+2
A:
You can now have a collection of references to base class objects and put references to derived classes objects there, call the virtual function through any of the references without knowing the actual derived class and have the most derived overriden function called each time. That's called polymorphism.
sharptooth
2009-08-24 12:59:33
+2
A:
The need is that derived classes can override, and it behaves as you'd expect.
The converse is when creating a method on a derived class, specifying the new keyword -- in this situation the version of the function that matches the type of the variable is used, so:
derived foo = new derived();
base foo2 = foo;
foo2.bar(); // If bar() is virtual, and overriden in derived, it will use that implementation.
foo.bar(); // if bar() is not virtual, this may be calling a completely different function, if derived defines a new version
Rowland Shaw
2009-08-24 13:00:49