Virtual functions
|
In many object oriented programming languages such as C++, C#, VB.NET, a virtual function is a function that can be overridden with specialized implementations in subclasses.
For example, a base class Animal
could have a virtual function eat
. Subclass Fly
would implement eat
differently than subclass Wolf
, but you can invoke eat
on any base class instance.
This allows you to process a list of objects of class Animal
, telling each in turn to eat (by calling eat
), with no knowledge of what kind of animal may be in the list. You also do not need to have knowledge of how each Animal
eats.
Abstract Class and Pure Virtual Functions
Virtual functions in C++ are functions that will be redefined in derived classes. When defined as null, they are pure virtual functions (example: class B{virtual void apurevirtualfunction() = 0;}
). The presence of pure virtual functions implies that the class containing them is an abstract class, and the function prototype is then used as a stub. The advantage of abstracting a function in this manner is that you do not need to know how the function will be implemented, instead, you only need to know that the module or the abstract class needs a certain functionality. Actual definition can be done later or at the overloaded function of the derived classes. Since they are primarily used as stubs, they are often left empty.
For the compiler, they also signal to check the function definition at the derived class first. The compiler creates a list of pointers to all the virtual functions called the vtable
or virtual table.