Object Oriented Programming-Polymorphism - Virtual Functions
Object Oriented Programming-Polymorphism - Virtual Functions
C++
PREPARED BY: ENGR. REEMA QAISER KHAN
SCHEME OF PRESENTATION
Polymorphism/Virtual Functions
Normal Member Functions Accessed with Pointers
Virtual Member Functions Accessed with Pointers
References
Polymorphism/Virtual Functions
The word polymorphism means having many forms. Typically, polymorphism occurs when there
is a hierarchy of classes and they are related by inheritance.
C++ polymorphism means that a call to a member function will cause a different function to be
behavior can be overridden within an inheriting class by a function with the same signature.
This concept is an important part of the polymorphism portion of object-oriented programming (OOP).
ptr=&dv1;
ptr->show();
Cont.
5
The Derv1 and Derv2 classes are derived from class Base. Each of these classes has a member function
show().
Now the question is, when you execute the line
ptr->show();
What function is called? Is it show() of Base, or show() of Derv1, or show() of Derv2?
Which of the show() function is called here? The output from the program answers these questions:
Base
Base
Base
show()
&Derv1
Derv1
ptr->show()
show()
Derv2
ptr
show()
&Derv2
ptr->show()
ENGR. REEMA QAISER KHAN
Cont.
ENGR. REEMA QAISER KHAN
Derv1
Derv2
Now, as you see, the member functions of the derived classes, not the base class, are executed. We
change the contents of ptr from the address of Derv1 to that of Derv2, and the particular instance of
show() that is executed also changes. So the same function call
ptr->show();
Executes different functions, depending on the contents of ptr. The rule is that the compiler selects the
function based on the contents of the pointer ptr, not on the type of the pointer, as in the previous
example where we did not use virtual keyword.
10
Base
show()
&Derv1
Derv1
ptr->show()
show()
Derv2
ptr
show()
&Derv2
ptr->show()
ENGR. REEMA QAISER KHAN
11
REFERENCES
1- Book: Object-Oriented Programming in C++, Robert Lafore, 4th Edition,
pages(504-509).
12