NU-Lec 10_Virtual Functions and Polymorphism - I
NU-Lec 10_Virtual Functions and Polymorphism - I
Lecture No. 10
Virtual Functions and Polymorphism
Objectives
• Polymorphism in C++
• Pointers to derived classes
• Introduction to virtual functions
Polymorphism
• The Greek word polymorphism means one name,
many forms.
t1.draw ();
cout << “The area is “ << t1.GetArea ( );
c1.draw ();
cout << “The area is “ << c1.GetArea ();
r1.draw ();
cout << “The area is “ << r1.GetArea ();
c2.draw ();
cout << “The area is “ << c2.GetArea ();
return 0;
}
10
• baseClassObject = derivedClassObject;
– This will work
• Remember, the derived class object has more members than the base
class object
– Extra data is not given to the base class
• derivedClassObject = baseClassObject;
– Error
• Unless an assignment operator is overloaded in the derived class, data
members exclusive to the derived class will be unassigned
• Base class has less data members than the derived class
• Some data members missing in the derived class object
11
Exploiting inheritance
Polymorphism Defined
Polymorphism
• extending inheritance
• Polymorphism means using the same syntax to do
different things depending on the context
• Binding:
Refers to the process that is used to convert identifiers (such
as variable and function names) into machine language
addresses.
• Static binding or Early binding
– In most programming languages and in most cases the
variables are bound to a specific type at compile time
• Static binding
• Dynamic binding or Late binding
• The type of the variable can change at run time
• Using pointers to classes related by inheritance in C+
+
Polymorphism vs. Inheritance
18
Pointers to Derived Classes
• With the help of pointers to derived classes, we can create
an array of base class objects, and that array can hold
objects of different derived classes
Line *p[4];
p[0] = new Triangle (3, 4, 5, 19 );
p[1] = new Circle (3, 4, 5 );
p[2] = new Rectangle ( 3, 4, 10 , 20 );
p[3] = new Cylinder ( 3, 4, 5, 10 );
for ( int loop = 0; loop < 4; loop ++ )
{ p[loop]->draw ();
cout << “The area is “ << p[loop]->GetArea ( );
}
Pointers to Derived Classes (contd.)
• Using a base class pointer (pointing to a derived
class object) we can access only those members of
the derived object that were inherited from the
base.
Run-time polymorphism
Requirements for Virtual Functions
Reading References
Polymorphism:
• http://www.cplusplus.com/doc/tutorial/polymorphism/
• http://www.cs.bu.edu/teaching/cpp/polymorphism/intro/
Virtual Functions
• Rober Lafore Chapter 11, Page 504