Polymorphism happens as program is running , when the type of the parameter passed in is different from it's definition(usually defined as a parent class pass a subclass), and we will call the parameter's method in this method.
there should be a rule whether to call the parent's method or call the subclass' method.
for static binding, it depends on the type of the definition;
for dynamic binding, it depends on the type of the object we passed in.
attention:
in order to realize dynamic binding, besides the virtual key words, we should define the function's parameter as &.
#include "stdafx.h"
#include <iostream>
using namespace std;
class CParent
{
public:
virtual void name(){cout<<"parent";}
};
class CSon:public CParent
{
public:
virtual void name(){cout<<"son";}
};
class CDaughter:public CParent
{
public:
void name(){cout<<"daughter";}
};
void callName(CParent &person)
{
person.name();
}
int _tmain(int argc, _TCHAR* argv[])
{
CSon son1;
callName(son1);
int i;
cin>>i;
return 0;
}
the out put is parent;
this one's output is son
#include "stdafx.h"
#include <iostream>
using namespace std;
class CParent
{
public:
virtual void sayname(){cout<<"parent";}
void name(){sayname();};
};
class CSon:public CParent
{
public:
virtual void sayname(){cout<<"son";}
//virtual void name(){sayname();}
};
class CDaughter:public CParent
{
public:
void name(){cout<<"daughter";}
};
void callName(CParent &person)
{
person.name();
}
/*void callName(CSon &son)
{
son.name();
}*/
int _tmain(int argc, _TCHAR* argv[])
{
CSon son1;
//CParent parent1;
callName(son1);
int i;
cin>>i;
return 0;
}
当父类和子类都有相同函数定义的时候,如何确定到底调用的是父类的函数还是调用的子类的函数。
1. 对象式
func()
{
CClass object;
object.method();
}
不管method是否有virtual,都是先严格按照object的对象类型。当object没有该方法,再去调用父类。
2.指针式
Parent p;
Son s1
Son *pSon = &p;
p->func() // parent's function
Son*pSon2 = &s1;
p->func()// son's funcion
严格按照指针实际指向的对象的类型,先去调用该类型的方法。如果没有再沿着父类向上找。
2.参数式(对象不是在函数中定义,而是从参数中传入)
func(Parent &object)
{
object.method()
}
如果method有virtual,并且定义参数为引用或者指针,则按照实际运行中传入对象的类型
否则按照func声明中参数的类型。