Polymorphism occurs three conditions
a: inheritance
two: virtual functions and virtual function overrides
three: parent pointers or references to sub-class objects
A simple fighting game code to achieve polymorphism
#include <the iostream> the using namespace STD; // original hero class Hero { public : virtual int values () // necessary condition virtual polymorphic { return 100 ; } }; // new hero class Superhero: public Hero { public : Virtual int values () { return 1000 ; } }; // original monster classMonster { public : int values () { return 999 ; } }; void Fight (Hero * P1, Monster * P2) // provides polymorphic interface can be written as reference in (hero & p1, monster & p2 ), but the main function mass should be subject incoming parameters, under certain circumstances, may be substituted for reference pointers { IF (P1-> values ()> P2-> values ()) COUT << " the Hero winned " << endl; the else COUT << " the falsed Hero " << endl; } int main ( int argc,four** the argv) { Hero h1 of; Monster M1; Fight ( & h1 of, & M1); // original hero Superhero S1; Fight ( & S1, & M1); // new hero COUT << s1.values (); // this case the output is a superhero values, to call the hero of values, it is necessary scope << s1.hero :: values COUT (); return 0 ; }
Second, virtual reflected destructor
Virtual destructor (delete): base class char * p, by way of open pointer size when and configured i.e. p = new char [20];
if the base class pointer to a derived class, and delete the base class pointer, and finally destructor of the base class, because it as part of the base class, and a memory leak
solution: because when calling the destructor of the derived class will automatically call the destructor of the base class
so the base class destructor declared virtual, and then delete the base class pointer to an object of a derived class will