Thursday, March 6, 2008

virtual function -- the key to OOP

I actually never understood this concept until I had to code something in it. It was really awesome to realize what this virtual keyword can do. I actually believe that we should make all our class member functions virtual. Though this may generate some sort of an overhead but I feel that the compiler optimization should take care of it. The main use of this virtual keyword is in cases where we need to reuse certain classes. Often the framework in which we are working in identifies a single base class. so now when this framework wants to make use of the new class, it can do so without any problem. Though the framework calls the same function it would now be able to access the function modified for the new class. Often when we have written code for drawing certain objects on the screen, we would have anticipated line, circle, triangle and a polygon. But later we realize the need for having quadrilaterals and squares also as they are frequently used. So in this case had we made use of a base class shapes, which would have had a virtual function called draw. The framework would just call 'draw' for the entire list of shapes it had. Since the 'draw' is virtual, you can expect the object specific 'draw' to be called. So you can easily extend you library. This is also called factory pattern. But this is not the only pattern to use virtual, there are others also but this example give us a very good reason to why we need virtual function, though there are ways to live without it also. But why use a knife to cut a tree when u have an axe.