how to use virual function in real time example
Answer Posted / yuva
You use virtual functions when you want to override a
certain behavior(read method) for your derived class than
the one implemented for the Base class and you want to do so
at run-time through an pointer to Base class.
The classical example is when you have a base class called
Shape and concrete shapes(classes) which derive from it.
Each concrete class overrirdes(implements a virtual method)
called Draw().
The class hierarchy as follows:
Class hierarchy
The following snippet shows the usage of the example, it
creates an array of Shape class pointers wherein each points
to distinct derived class object. At run-time invoking
Draw() method results in calling of the method overriden by
that derived class and the particular Shape is drawn(rather
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
storing addresses of the Derived class objects provides a
loose coupling in the way that the program does not have to
change drastically if a new concrete derived class of shape
is added anytime because the are minimal code segments which
actually use(depend) on the concrete Shape type.
The above is a good example of Open Closed Principle of the
famous SOLID design principles.
| Is This Answer Correct ? | 0 Yes | 0 No |
Post New Answer View All Answers
What is difference between && and & in c?
How is a macro different from a function?
When I tried to go into a security sites I am denied access and a message appeared saying 'applet not initialize'. How can I rectify this problem.
Do character constants represent numerical values?
Explain what would happen to x in this expression: x += 15; (assuming the value of x is 5)
What is the deal on sprintf_s return value?
What is a program?
Why pointers are used?
What is the difference between single charater constant and string constant?
Linked list is a Linear or non linear explain if linear how it working as a non linear data structures
Do string constants represent numerical values?
What's a good way to check for "close enough" floating-point equality?
What is difference between arrays and pointers?
What is the process of writing the null pointer?
What are the 3 types of structures?