here i have discussed virtual functions using easy to understand examples.
A virtual function is a member function of a class, whose functionality can be over-ridden in its derived classes. It is one that is declared as virtual in the base class using the virtual keyword. The virtual nature is inherited in the subsequent derived classes.
The difference between a non-virtual member function and a virtual member function is, the non-virtual member functions are resolved at compile time whereas virtual members are resolved at runtime.
in this code we have the implementation of virtual functions and their use in c++.
In the above example, the pointer is of type base but it points to the derived class object. The method display() is virtual in nature. Hence in order to resolve the virtual method call, the context of the pointer is considered, i.e., the display method of the derived class is called and not that of the base. If the method was non virtual in nature, the display() method of the base class would have been called.Code:#include <iostream.h> class base { public: virtual void display() { cout<<”\nBase”; } }; class derived : public base { public: void display() { cout<<”\nDerived”; } }; void main() { base *ptr = new derived(); ptr->display(); }
Virtual methods should be used judiciously as they are slow due to the overhead involved in searching the virtual table. They also increase the size of an object of a class by the size of a pointer.
Last edited by Chinmoy; 03-18-2008 at 04:58 AM.
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks