1. Look directly at the following code:
#include <iostream>using namespacestd;class Base{ Public: voidWho () {cout<<"This is the class of base!"<<Endl; }};classDerivel1: Public Base{ Public: voidWho () {//General overloaded Functionscout<<"This is the class of derivel1!"<<Endl; }};classDerivel2: Public Base{ Public: voidWho () {cout<<"This is the class of derivel2!"<<Endl; }};intMain () {Baseobj1,*p; Derivel1 Obj2; Derivel2 obj3; P=&obj1; P-Who (); P=&Obj2; P-Who (); ((Derivel1*) p)Who (); P=&obj3; P-Who (); ((Derivel2*) p)Who (); Obj2.who (); Obj3.who (); return 0;}
This introduces the concept of why virtual functions are introduced —————— in order to achieve polymorphism
2. For the virtual function in memory distribution, look at the blog can be deeply realized:
http://blog.csdn.net/zhangliang_218/article/details/5544802
PS: Note the relationship between virtual functions and overloaded functions
PS: Note the difference from Java polymorphism
3. Calling virtual functions in constructors and destructors
The compilation system uses static linking of calls to virtual functions in constructors and destructors, that is, the virtual functions they call are the functions defined in their own class or base class, rather than in any derived class.
Examples are as follows:
#include <iostream>using namespacestd;class Base{ Public: Base(){ } Virtual voidVF () {cout<<"BASE::VF () called"<<Endl; }};classSon Public Base{ Public: Son () {VF (); } voidg () {VF (); }};classGrandson: Publicson{ Public: Grandson () {}voidVF () {cout<<"GRANDSON::VF () called\n"; }};intMain () {grandson GS; GS.G (); return 0;}
The results are as follows:
The result of the program is that when the object GS of the grandson class is established, the base class child objects it contains are established before the new members defined in the derived class are established.
4. Empty virtual functions
A derived class does not necessarily have to implement a virtual function in a base class, and if a derived class wants to access a virtual function through a virtual function mechanism, it must establish a virtual function path from the base class to the derived class.
#include <iostream>using namespacestd;class Base{ Public: Virtual voidprint () {cout<<"class base\n"; }};classSon Public Base{ Public: Virtual voidPrint () {//void function }};classGrandson: Publicson{ Public: Virtual voidprint () {cout<<"class grandson!\n"; }};voidShowBase*p) {P-print ();}intMain () {Base*pbase=New Base; Son*pson=NewSon; Grandson*pgrandson=Newgrandson; Show (PBase); Show (Pson); Show (Pgrandson); return 0;}
Operation Result:
5. Pure virtual functions and abstract classes
Virtual functions and polymorphism in C + +