Virtual-Functions
Virtual-Functions
Example
A virtual function is a member function in the base
class that we expect to redefine in derived classes.
Basically, a virtual function is used in the base class
in order to ensure that the function is overridden.
This especially applies to cases where a pointer of
base class points to an object of a derived class.
This provides flexibility and code reusability in object-
oriented programming.
b y RISHI KUMAR
(1MV23IS087)
D e c l a ra t i o n o f Virtual Functions
class Base
{
public:
Virtual Keyword virtual void print()
{
A virtual function is declared using the 'virtual' // code
keyword in the base class. This function can be }
};
overridden in derived classes.
class Derived : public Base
{
public:
SYNTAX : void print()
{
virtual return_type Function_name() // code
{ }
//code };
}
int main()
Example {
base* bptr; //pointer object of base class
#include <iostream> derived d; //object of derived class
using namespace std; bptr = &d; // pointer of base class points to an
object of a derived class.
class base {
public: // Virtual function, binded at runtime
virtual void print() { cout << "print base class\n"; } bptr->print();
void show() { cout << "show base class\n"; } // Non-virtual function, binded at compile time
}; bptr->show();
Flexibility C o d e Reuse
Polymorphism with Virtual functions allow
virtual functions enables code reuse by providing
writing more flexible and a common interface in
extensible code, as new the base class, with
derived classes can be specifi c implementations
added without in derived classes.
modifying existing code.