0% found this document useful (0 votes)
3 views

Virtual-Functions

cpp

Uploaded by

kumarrishi5826
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Virtual-Functions

cpp

Uploaded by

kumarrishi5826
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Virtual Functions

Virtual functions in C++ are a powerful feature that enable dynamic


binding and polymorphism, allowing objects of derived classes to be
treated as objects of a base class. This provides flexibility and code
reusability in object-oriented programming.

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.

Flexibility Runtime Efficiency


Polymorphism with virtual The runtime determination of
functions enables writing more the correct function to call can
flexible and extensible code, as add a small overhead, but the
new derived classes can be benefits of polymorphism often
added without modifying outweigh this cost.
existing code.
Benefits of Virtual
Functions

Polymorphism Code Reuse


Virtual functions enable Virtual functions provide a
polymorphic behavior, allowing common interface in the base
objects of derived classes to be class, allowing derived classes to
treated as objects of a base class. reuse and customize the
implementation.

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.

You might also like