In programming languages, polymorphism means that some code or operations or objects behave differently in different contexts.
For example, the +
(plus) operator in C++:
4 + 5 <-- integer addition 3.14 + 2.0 <-- floating point addition s1 + "bar" <-- string concatenation!
In C++, that type of polymorphism is called overloading.
Typically, when the term polymorphism is used with C++, however, it refers to using virtual
methods, which we'll discuss shortly.
Assume we have Employee class , Manager class , and programmer class.
and the Manager class inheritance from Employee class.
Intuition , we know the a manager is also a employee , but a employee can not be a manager .
so if we create a Employee object , this employee may be manager or programmer ,
so we can assign this object to manager or programmer ,
but in the contrast , we can not assign a manager object to employee , because not all emplyees are managers.
This is the concept of polymotphism.
class
Base
{
protected
:
int
m_nValue;
public
:
Base(
int
nValue)
: m_nValue(nValue)
{
}
const
char
* GetName() {
return
"Base"
; }
int
GetValue() {
return
m_nValue; }
};
class
Derived:
public
Base
{
public
:
Derived(
int
nValue)
: Base(nValue)
{
}
const
char
* GetName() {
return
"Derived"
; }
int
GetValueDoubled() {
return
m_nValue * 2; }
};
int
main()
{
using
namespace
std;
Derived cDerived(5);
// These are both legal!
Base &rBase = cDerived;
Base *pBase = &cDerived;
cout <<
"cDerived is a "
<< cDerived.GetName() <<
" and has value "
<< cDerived.GetValue() << endl;
cout <<
"rBase is a "
<< rBase.GetName() <<
" and has value "
<< rBase.GetValue() << endl;
cout <<
"pBase is a "
<< pBase->GetName() <<
" and has value "
<< pBase->GetValue() << endl;
return
0;
}