Pointer object in C++->why do we need virtual function in C++-Polymorphism in minutes

Pointer object

We can create pointer object of a base class as well as pointer object of derived class.

Pointer object of a base class can point to object of a derived class due to inheritance process [i.e because features of base class are inherited in derived class].

 

However, pointer object of derived class can’t point to base class object and can only point to derived class object [ie because inheritance process do not work in reverse order.]

Image to understand it easily-:

Now we have said that base class pointer object can point to derived class. As well as derived class ptr object although can’t point to base class but can point to itself. [remember this before continuing further]

 

Base class pointer object pointing to derived class object can access only those members that are inherited from base class.

 

However derived class pointer object pointing to derived class object can access all the features of derived class.

Image for understanding this concept-:

From above, we can conclude accessibility of the pointer depends upon the types of pointer ie either base or derived [and not to anything else like the object that are pointing to, remember “not depending to object it is pointing to”, in the virtual function this is our problem statement].

Output-:

value of m=5

value of m=5

and value of D=15

 

Need of virtual function-:

We have seen earlier that accessibility of the pointer i.e base or derived depends upon the type of pointer rather than object to which it is pointing, so, if we want to access the function depending upon the object to which it is pointing, we use the concept of virtual function.

 

Virtual function is used to achieve run time polymorphism

 

i.e compiler access different versions of functions according to the object[depending upon the object] pointed to by pointer object[ during the runtime only].

 

If it is still not clear then an example program will help you to understand this concept.

There are few rules and regulations related to using virtual functions in our program-:

1)Virtual function is initially defined in base class and redefined in each derived classes which are derived from base class.

 

2)And the next rule is that the keyword virtual is optional in each derived classes.

 

 

Characteristics of virtual function are given as shown in figure below.

Q)Write an example program of virtual function-:

Output-:

animal class

cow class

dog class

The difference between with virtual function and without virtual function is given below-:

We will remove virtual keyword in the above program.

 

Output-:

animal class

animal class

animal class

So for now, this is the reason why we use virtual keyword in function to show all the derived class output as well and not only the base class output.

Be the first to comment

Leave a Reply

Your email address will not be published.


*