which means (in Greek) ‘the ability to take more than one form’. In general
polymorphism is the attribute that allows one interface to control access to a
operation in a manner customized to the object. Without polymorphism, you
would have to use a separate module or method name for a method that
multiplies two numbers and one that multiplies three numbers. Just as a blender
can produce juice regardless of whether you insert two fruits or three vegetables,
using a polymorphic, object-oriented multiplication function call, will produce a
correct product whether the input is two integers or three floating point numbers.
When you master polymorphism in the real world, you understand that you use
different methods to drive a car, to drive a golf ball, and to drive home a point.
This is how the English language works; you understand words based on their
language, you take a big step toward producing objects that function like their
real-world counterparts.
13
Introduction to C++
A real world example of polymorphism can be an Air–conditioner. The Air–
conditioners work the same way whether they are from Voltas, Blue star or
Samsung company. The interface (cooling) is the same no matter what type of
cooling mechanism is used.
The same concept can be applied to programming. For example consider the
operation of addition. The operator ‘+’ can be used to add two integers or floats.
Further the same operator can be used to concatenate two string or add a float
and a double value. This process of an operator acquiring different behaviour in
different instances is known as Operator Overloading.
Polymorphism of a function is the occurrence of a function name in different
forms, regarding the number and type of parameter list. When a single function
name is used to perform different types of tasks, it is referred to as function
overloading. For example a function called sort() may be used to sort a list of
integers, floats or strings.
Polymorphism on objects, is implementing a general class of operations in
the same way even though specific actions with each operation may differ.
Polymorphism is used in the implementation of inheritance.
Figure 1.5 illustrates a class called operation and a member function called
Add(). A single function Add() is used to perform different types of tasks such as
adding two integers, adding two floating–point numbers or adding two strings.
This is implemented using function overloading or function polymorphism.
Add()
Add(int a, int b)
Add(float x, float y)
Add(char *S1, char *S2)
Do'stlaringiz bilan baham: