how to use virual function in real time example



how to use virual function in real time example..

Answer / 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

More C Interview Questions

1.what are local and global variables? 2.what is the scope of static variables? 3.what is the difference between static and global variables? 4.what are volatile variables? 5.what is the use of 'auto' keyword? 6.how do we make a global variable accessible across files? Explain the extern keyword? 7.what is a function prototype? 8.what does keyword 'extern' mean in a function declaration?

0 Answers  


Explain the use of 'auto' keyword

0 Answers  


What is the value of h?

0 Answers  


write a “Hello World” program in “c” without using a semicolon?

9 Answers   CTS, TCS, Wipro,


What do the functions atoi(), itoa() and gcvt() do?

0 Answers   Aspire, Infogain,






what does keyword ‘extern’ mean in a function declaration?

1 Answers   Emerson,


What is pointer and structure in c?

0 Answers  


int arr[] = {1,2,3,4} int *ptr=arr; *(arr+3) = *++ptr + *ptr++; Final contents of arr[]

6 Answers   Hughes,


if a person is buying coconuts of Rs10,and then sell that coconuts of Rs9,with the loss of one rupee.After that the person became a millaniore.how?

9 Answers   Wipro,


Can include files be nested? How many levels deep can include files be nested?

0 Answers   Aspire, Infogain,


Is calloc better than malloc?

0 Answers  


Why is c used in embedded systems?

0 Answers  


Categories