What are Virtual Functions ? Why do we need Virtual Functions? Explain with an example.

A function that is defined in a base class but overridden by the derived class is called a virtual function. To create virtual functions precede the function declaration in the base class with the keyword virtual. When a class containing a virtual function is inherited the derived class overrides the virtual function with its own definition. Virtual functions are like member functions however what makes them different is the capability to support run time polymorphism when accessed via a pointer. A base class pointer can point to an object of a derived class. When a base class pointer points to an object of a derived class that contains a virtual function, C++ determines which function version to call based on the type of object pointed by the base class pointer. This is runtime polymorphism as it can be determined at run time. In this way when different objects are pointed to then different versions of virtual functions are executed. Whenever a virtual function is defined all aspects of its prototype should match. Also virtual functions should be non static members of the class and they cannot be friend functions too. E.g. class base { public: virtual void display (); }; class derived: public{ public: virtual void display ();};base *p, b;derived d1, d2;p = &b;p->display (); //calls base class functionp = &d1;p->display (); //calls derived class function