A virtual function is a member function which is declared within the base class and is re-defined (Override) by the derived class. When you allude to a derived class object utilizing a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function.
Following things are important to compose a C++ program with runtime polymorphism (utilization of virtual capacities)
1) A base class and a derived class.
2) A function with the same name in base class and derived class.
3) A pointer or reference of base class type pointing or referring to an object of derived class.
EXAMPLE: –
#include<iostream>
using namespace std;
class Base {
public:
virtual void show() { cout<<” In Base \n”; }
};
class Derived: public Base {
public:
void show() { cout<<“In Derived \n”; }
};
int main(void) {
Base *xy = new Derived;
xy->show(); // RUN-TIME POLYMORPHISM
return 0;
}
Output: In Derived
Regards,
Nitesh Bavishiya