C++ Programming Code Examples C++ > Beginners Lab Assignments Code Examples Program for Virtual Function: Program for Virtual Function: A virtual function is a special form of member function that is declared within a base class and redefined by a derived class. The keyword virtual is used to create a virtual function, precede the function's declaration in the base class. If a class includes a virtual function and if it gets inherited, the virtual class redefines a virtual function to go with its own need. In other words, a virtual function is a function which gets override in the derived class and instructs the C++ compiler for executing late binding on that function. A function call is resolved at runtime in late binding and so compiler determines the type of object at runtime. #include using namespace std; class b { public: virtual void show() { cout<<"\n Showing base class...."; } void display() { cout<<"\n Displaying base class...." ; } }; class d:public b { public: void display() { cout<<"\n Displaying derived class...."; } void show() { cout<<"\n Showing derived class...."; } }; int main() { b B; b *ptr; cout<<"\n\t P points to base:\n" ; ptr=&B; ptr->display(); ptr->show(); cout<<"\n\n\t P points to drive:\n"; d D; ptr=&D; ptr->display(); ptr->show(); }