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
How are variables declared in c?
What is the use of typedef in structure in c?
Can you please explain the difference between strcpy() and memcpy() function?
Why doesnt that code work?
please send me the code for multiplying sparse matrix using c
What is the purpose of main( ) in c language?
What is this infamous null pointer, anyway?
Can we declare a function inside a function in c?
How do shell structures work?
#define f(g,h) g##h main O int i=0 int var=100 ; print f ("%d"f(var,10));} wat would be the output??
the process of defining something in terms of itself is called (or) in C it is possible for the functions to call themselves. A function called a) nested function b) void function c) recursive function d) indifinite function
What are local static variables?
Explain how can I remove the trailing spaces from a string?
What is gets() function?
What are terms in math?