Virtual functions and runtime polymorphism
A member function that has the keyword virtual used in its declaration in the base class and is redefined (Overridden) in the derived class is referred to as a virtual function. The late binding instruction instructs the compiler to execute the called function during runtime by matching the object with the appropriately called function. Runtime Polymorphism refers to this method.
Polymorphism is a term used to describe the capacity to assume several shapes. If there is a hierarchy of classes connected to one another by inheritance, it happens. Polymorphism, which is defined as "showing diverse traits in different contexts," can be summarised as "showing different characteristics in a variety of situations" and "polymorphism."
What is the use of virtual functions?
To achieve Runtime Polymorphism, virtual functions are primarily used. Only a base class type pointer (or reference) can enable runtime polymorphism. A base class pointer can also point to both objects from the base class and those from derived classes.
Also, without even knowing the type of derived class object, we can use virtual functions to compile a list of base class pointers and call any of the derived classes' methods.
What are the rules for virtual functions?
What is runtime polymorphism?
Runtime polymorphism is the process of binding an object at runtime with a capability. Overriding methods is one way to implement runtime polymorphism. At runtime, not at compilation time, the Java virtual machine decides which method to invoke. Additionally known as dynamic binding or late binding. The parent class's method is overridden in the child class, according to this concept. The term "method overriding" refers to the situation where a child class implements a method specifically that was supplied by one of its parent classes. You can see runtime polymorphism in the example that follows.
How do virtual functions work?
As mentioned below, the compiler performs two tasks if a class has a virtual function.
What are the limitations of virtual functions?