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


Please Help Members By Posting Answers For Below Questions

the real constant in c can be expressed in which of the following forms a) fractional form only b) exponential form only c) ascii form only d) both a and b

1907


What is the function of multilevel pointer in c?

672


How can I make it pause before closing the program output window?

582


Explain what is the benefit of using an enum rather than a #define constant?

725


What is the difference between int main and void main in c?

594






If errno contains a nonzero number, is there an error?

808


Why we use void main in c?

598


What is a shell structure examples?

592


What type of function is main ()?

590


to print the salary of an employee according to follwing calculation: Allowances:HRA-20% of BASIC,DA-45% of BASIC,TA-10%. Deductions:EPF-8% of BASIC,LIC-Rs.200/-Prof.Tax:Rs.200/- create c language program?

1574


differentiate built-in functions and user – defined functions.

629


Explain high-order and low-order bytes.

670


we need to calculating INCOME TAX for the person. The INCOME TAX is as follows:- First $10000/- of income : 4% tax Next $10000/- of income : 8% tax Next $10000/- of income : 11.5% tax above $10, 00,00/- : 15% tax What is the Solution of this Question ?

804


What is sizeof int in c?

605


What are the complete rules for header file searching?

677