Virtual-Functions
Virtual-Functions
by RISHI KUMAR
Defining Virtual Functions
Virtual Keyword Overriding Late Binding
A virtual function is declared using the Derived classes can override the virtual The specific function to be called is
'virtual' keyword in the base class. This function with their own determined at runtime, based on the
function can be overridden in derived implementation, providing polymorphic object type, not the reference type.
classes. behavior.
Example of Virtual
Functions
1 Base Class
The base class declares a virtual function, 'draw()', which
can be overridden in derived classes.
2 Derived Class
The derived class overrides the 'draw()' function, providing
its own implementation.
3 Polymorphic Behavior
When a derived class object is used through a base class
pointer, the overridden function is called at runtime.
Polymorphism and Virtual
Functions
Dynamic Binding Code Reuse
Virtual functions enable Virtual functions allow code
dynamic binding, where the reuse by providing a common
specific implementation is interface in the base class, with
determined at runtime based specific implementations in
on the object type. derived classes.
Extensibility Flexibility
The use of virtual functions makes Virtual functions provide flexibility
the code more extensible, as new in object-oriented programming,
derived classes can be added allowing for dynamic and adaptable
without modifying existing code. behavior.