انت هنا الان : شبكة جامعة بابل > موقع الكلية > نظام التعليم الالكتروني > مشاهدة المحاضرة

Polymorphism

الكلية كلية العلوم للبنات     القسم قسم الحاسبات     المرحلة 2
أستاذ المادة احمد علي حسين الجنابي       05/04/2016 19:55:30
Polymorphism

Having learned the basics of inheritance, creating an inheritance hierarchy, and
understanding that public inheritance essentially models an is-a relationship, it’s time
to move on to consuming this knowledge in learning the holy grail of object-oriented
programming: polymorphism. Program statements code: This is the part of a program
that performs actions and they are called methods.
In this lesson, you find out
What polymorphism actually means
What virtual functions do and how to use them
What abstract base classes are and how to declare them
What virtual inheritance means and where you need it

Basics of Polymorphism
“Poly” is Greek for many, and “morph” means form. Polymorphism is that feature of
object-oriented languages that allows objects of different types to be treated similarly.
This lesson focuses on polymorphic behavior that can be implemented in C++ via the
inheritance hierarchy, also known as subtype polymorphism.

Need for Polymorphic Behavior
In Lesson, “Implementing Inheritance,” you found out how Tuna and Carp inherit
public method Swim() from Fish as shown in example1 of Lesson “Implementing
Inheritance". It is, however, possible that both Tuna and Carp provide their own
Tuna::Swim() and Carp::Swim() methods to make Tuna and Carp different swimmers.
Yet, as each of them is also a Fish, if a user with an instance of Tuna uses the base class
type to invoke Fish::Swim(), he ends up executing only the generic part Fish::Swim()
and not Tuna::Swim(), even though that base class instance Fish is a part of a Tuna .
This problem is demonstrated in Example 1.

Polymorphic Behavior Implemented Using Virtual Functions
You have access to an object of type Fish, via pointer Fish* or reference Fish&. This
object could have been instantiated solely as a Fish, or be part of a Tuna or Carp that
inherits from Fish. You don’t know (and don’t care). You invoke method Swim() using
this pointer or reference, like this:
What you expect is that the object Fish swims as a Tuna if it is part of a Tuna, as a Carp
if it is part of a Carp, or an anonymous Fish if it wasn’t instantiated as part of a
specialized class such as Tuna or Carp. You can ensure this by declaring function
Swim() in the base class Fish as a virtual function:

المادة المعروضة اعلاه هي مدخل الى المحاضرة المرفوعة بواسطة استاذ(ة) المادة . وقد تبدو لك غير متكاملة . حيث يضع استاذ المادة في بعض الاحيان فقط الجزء الاول من المحاضرة من اجل الاطلاع على ما ستقوم بتحميله لاحقا . في نظام التعليم الالكتروني نوفر هذه الخدمة لكي نبقيك على اطلاع حول محتوى الملف الذي ستقوم بتحميله .