you use virtual functions when you want to override a certain behavior (read method) for your derived class rather than the one implemented for the base class and you want to do so at run-time through a pointer to the base class.
the classic example is when you have a base class called shape and concrete shapes (classes) that derive from it. each concrete class overrides (implements a virtual method) called draw().
the class hierarchy is as follows:
the following snippet shows the usage of the example; it creates an array of shape class pointers wherein each points to a distinct derived class object. at run-time, invoking the draw() method results in the calling of the method overridden by that derived class and the particular shape is drawn (or rendered).
shape *basep[] = { &line_obj, &tri_obj,
&rect_obj, &cir_obj};
for (i = 0; i < no_pictures; i++)
basep[i] -> draw ();
the above program just uses the pointer to the base class to store addresses of the derived class objects. this provides a loose coupling because the program does not have to change drastically if a new concrete derived class of shape is added anytime. the reason is that there are minimal code segments that actually use (depend) on the concrete shape type.
the above is a good example of the open closed principle of the famous solid design principles.
you use virtual functions when you want to override a certain behavior (read method) for your derived class rather than the one implemented for the base class and you want to do so at run-time through a pointer to the base class.
the classic example is when you have a base class called
shape
and concrete shapes (classes) that derive from it. each concrete class overrides (implements a virtual method) calleddraw()
.the class hierarchy is as follows:
the following snippet shows the usage of the example; it creates an array of
shape
class pointers wherein each points to a distinct derived class object. at run-time, invoking thedraw()
method results in the calling of the method overridden by that derived class and the particularshape
is drawn (or rendered).the above program just uses the pointer to the base class to store addresses of the derived class objects. this provides a loose coupling because the program does not have to change drastically if a new concrete derived class of
shape
is added anytime. the reason is that there are minimal code segments that actually use (depend) on the concreteshape
type.the above is a good example of the open closed principle of the famous solid design principles.