Virtual Functions in C++ with Example



By default, C++ matches a function call with the appropriate function definition at compile time. This is termed as static binding.
We can specify the compiler match a function call with the appropriate function definition at run time.
This is known as dynamic binding.
We can declare a function with the keyword virtual if we would like to compiler to use dynamic binding for that specific function.
When a class declares or inherits a virtual function is known as polymorphic class.

Example:

#include<iostream.h>
#include<conio.h>
class A
               {
                              public:
                              virtual void show()
                              {
                                             cout<<”Base Class”;
}
               };
class B : public A
               {
                              public:
                              void show()
                              {
                                             cout<<”Derived Class”;
}
               };
void main()
{
               clrscr();
               A ab;
               B ba;
               A *ptr;
               ptr =&ab;             //Dynamic Typing
               ptr ->show();       // Dynamic Binding
               ptr =&ba;             // Dynamic Typing
               ptr->show();        // Dynamic Binding
               getch();
}
Output:
Base Class
Derived Class

No comments:

Post a Comment