1#include <iostream>2#include <complex>3 using namespacestd; 4 5 classBase6 { 7 Public: 8Base () {cout<<"Base-ctor"<<Endl;} 9~base () {cout<<"Base-dtor"<<Endl;} Ten Virtual voidFint) {cout<<"base::f (int)"<<Endl;} One Virtual voidFDouble) {cout<<"base::f (Double)"<<Endl;} A Virtual voidGintI=Ten) {cout<<"base::g ()"<<i<<Endl;} - }; - classDerived: PublicBase the { - Public: -Derived () {cout<<"Derived-ctor"<<Endl;} -~derived () {cout<<"Derived-dtor"<<Endl;} + voidF (complex<Double>) { -cout<<"derived::f (complex)"<<Endl; + } A voidGintI= -){ atcout<<"derived::g ()"<<i<<Endl; - } - }; - intMain () - { -cout<<sizeof(Base) <<endl;//sizeof for instance, no member functions, each instance has a virtual function table, subclasses share the virtual function table of the parent class so sizeof size incout<<sizeof(Derived) <<endl;//as to why a virtual function (commented out two) and three virtual functions are the same size, because no matter how many virtual functions are saved in a virtual function table, and the object only holds a virtual function table pointer to the virtual function, so no matter how many virtual functions, size is a virtual function pointer - to Base B; + Derived D; -Base *pb=NewDerived;//the parent pointer points to the subclass object, which is required for polymorphism theB.F (1.0); *D.F (1.0); $Pb->f (1.0);//not polymorphic, the function parameter is different, for the new function. Panax Notoginseng B.G (); - D.G (); thePb->g ();//polymorphism, dynamic binding, method of invoking a class that is actually passed to the pointer + DeletePB; A return 0; the}
1#include <iostream>2 using namespacestd;3 classBase4 { 5 Public: 6 Base ():d ATA (count)7 {8cout<<"Base-ctor"<<Endl;9++count;Ten } One~Base () A { -cout<<"Base-dtor"<<Endl; ---count; the } - Static intcount; - intdata; - }; + intBase::count; - classDerived: PublicBase + { A Public: at Derived ():d ATA (count), data1 (data) - { -cout<<"Derived-ctor"<<Endl; -++count; - } -~Derived () in { -cout<<"Derived-dtor"<<Endl; to--count; + } - Static intcount; the intdata1; * intdata; $ };Panax Notoginseng intDerived::count=Ten; - intMain () the { +cout<<sizeof(Base) <<Endl; Acout<<sizeof(Derived) <<Endl; the +base* PB =Newderived[3]; -cout<<pb[0].data<<Endl; $cout<<pb[1].data<<Endl; $cout<<pb[2].data<<endl;//Why it is 10 don't understand ... -cout<< ((static_cast<derived*> (PB)) +2)->data1<<Endl; - Delete[] PB;//because the destructor is not a virtual function, delete executes only the destructor of the base class and cannot execute the destructor of the subclass so the count of the subclass is the -cout<<base::count<<Endl;Wuyicout<<derived::count<<Endl; the return 0; -}
Reference: http://blog.csdn.net/hackbuteer1/article/details/7883531
C + + virtual function and multi-state instance analysis