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 oops c?
Explain what header files do I need in order to define the standard library functions I use?
Explain what are bus errors, memory faults, and core dumps?
What is the code in while loop that returns the output of given code?
Describe the difference between = and == symbols in c programming?
Can i use “int” data type to store the value 32768? Why?
Are the variables argc and argv are local to main?
Why do we use int main?
Why we use conio h in c?
What is difference between structure and union?
Write a program to find factorial of a number using recursive function.
What are the output(s) for the following ? #include char *f() {char *s=malloc(8); strcpy(s,"goodbye")} main() { char *f(); printf("%c",*f()='A'); }
Do you know pointer in c?
How arrays can be passed to a user defined function
What does void main () mean?