Prepare knowledge
There are three prerequisites for polymorphism (polymorphism) in C + +:
- An inheritance architecture must exist.
- Some classes in the inheritance architecture must have virtual member functions with the same name (virtual keyword)
- A pointer to at least one base class type or a reference to a base class type. this pointer or reference can be used to invoke the virtual member function .
List of programs: Polymorphism in C + + (Runtime departure binding)
#include <iostream>using namespace Std;class ctradesperson{//base classpublic:virtual void Sayhi () {cout<< "Just hi." <<endl;}}; Class Ctinker:public ctradesperson{//drived class 1public:virtual void Sayhi () {cout<< "Hi, I Tinker." <<endl;}}; Class Ctailor:public ctradesperson{//drived class 2public:virtual void Sayhi () {cout<< "Hi, I Tailor" <<endl; }};int Main () {ctradesperson* p;//pointer to base classint which;//prompt user for a number//*** 1 ==ctadesperson// 2 ==ctinker//3 ==ctailordo{cout << "1 = = Ctradesperson, 2 = = Ctinker, 3 = = Ctailor" <<endl;cin >>which ;} while (which<1| | WHICH>3); Set pointer p depending on user choiceswitch (which) {case 1:p = new Ctradesperson; break;case 2:p = new Ctinker; Case 3:p = new Ctailor; break;} Invoke the Sayhi method via the Pointerp->sayhi (); Runt-time binding in Effectdelete p; Free the Dymanicall y allocated Storagereturn 0;}
Description of the program manifest
The program listing procedure clarifies the polymorphism and its three prerequisites:
- There is an inheritance architecture, Ctradesperson is the base class, and Ctinker and Ctailor are derived classes of Ctradesperson.
- There is a virtual member function called Sayhi in the inheritance architecture, which is defined once in each of the three classes, so there are three different definitions (but the function name is the same).
- P is a pointer to a base class type. The data type of P in this program list is ctradesperson*. The pointer p is used to implement a call to the virtual member function Sayhi.
Test data
In the course of a run of the program, we enter data 1 and we get the following result:
When we enter data 3, we get the following result:
For more discussion and exchange on program language, please follow this blog and Sina Weibo songzi_tea.
Program Cornerstone: C + + polymorphism Prerequisites