+ 1
What is polymorphism?
What is the use of it in a program?
3 Answers
+ 3
Polymorphism is a technique that enables you to abstractly deal with details. Sounds weird? I'll get to it after some of the technical details. :-)
Polymorphism comes in two tastes: static and dynamic polymorphism.
You have *static* polymorphism, if you *overload* a function (doesn't have to be in a class, can be "free"). Overloading is when you have multiple functions with the same name that differ in their signature, i.e. in their parameters (number and / or types) and their implementation.
You have *dynamic* polymorphism, if you *override* a method in a class. Overriding is when you have a new implementation for a method in a subclass for a virtual method of the exact name and signature in one of the super classes.
Dynamic polymorphism is only available via pointers and references to objects.
So how does polymorphism actually fulfill the purpose that I claimed in the beginning?
It provides different implementations ("details" from the short answer) by using the type system to distinguish between function / method implementations.
Examples:
#include <iostream>
// static polymorphism
int func(int a, int b) {
std::cout << "func(int, int)\n";
return 1;
}
int func(float a, float b) {
std::cout << "func(float, float)\n";
return 2;
}
float func(int a) {
std::cout << "func(int)\n";
return 3.0;
}
// dynamic polymorphism
class A {
public:
virtual void func2() {
std::cout << "You are in A::func2\n";
}
};
class B: public A {
public:
virtual void func2() {
std::cout << "You are in B::func2\n";
}
};
int main() {
func(1, 1);
func(1.0f, 1.0f);
func(1);
A* pa = new B();
pa->func2();
delete pa;
}
Play with it and get some hands-on knowledge :-)
+ 1
polymorphism is a feature provided by oop
it has following features:
1. It allows you to invoke methods of derived class thought base class references during runtime.
and
2. It has ability for classes to provide different type of implementation that is called throught the same name.
- 1
poly = many
morphism = forms