"why use virtual functions? " Code Answer

1

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.

By Ali Demirci on January 8 2022
Only authorized users can answer the Search term. Please sign in first, or register a free account.