In: Computer Science
Examine each of the following code fragments to identify the type of polymorphism it
represents (overloading, coercion, parametric, or subtype)
double x, y;
x = 5;
y = 4;
print("result= " + x / y);
b.
int sum(int a, int b) {
std::cout << "Sum of ints\n";
return a + b;
}
double sum(double a, double b) {
std::cout << "Sum of doubles\n";
return a + b;
}
int main() {
std::cout << "The sum is " << sum(7, 8) << std::endl;
std::cout << "The sum is " << sum(7.2, 8.2) << std::endl;
}
The given code fragment represents to overloading polymorphism:
What is overloading polymorphism?
Overloading in Object oriented programing means the using the same name of functions in the program with different parameters and return types to perform different tasks.
Why given code has overloading:
The code uses sum() user defined method with two different type of agruments and return type i.e function sum is overloaded.
Below sum() function will accept int type parameter a and b and return an int type value
int sum(int a, int b){
std::cout<<”Sum of ints \n”;
return a+b;
}
Overloaded sum() function will accept double type parameter a and b and return a double type value
double sum(double a, double b){
std::cout<<”Sum of doubles \n”;
return a+b;
}
Thus from above description it can be stated that it is overloaded polymorphism.
Why the given fragment is not of type coercion, parametric, or subtype polymorphism:
· Coercion is a polymorphism where the type of a polymorphism where the type of an object is casted to another type. The given segment does not convert the type of variables, thus the code does not have this type of polymorphism
· Parametric polymorphism is a way to perform same action of any data type e.g. largest(1,2), largest(a,b) will return largest between two passed parameters. This is not the polymorphism type shared in given code fragment.
· SubType polymorphism used one base class and one or more derived class tp achive the goal of polymorphism. The given code does not have many classes in it, thus it is not of this type of polymorphism.