This example illustrates the following issues:
Virtual functions are defined, called (pointers or references to external functions, member functions), constructors and destructors call virtual functions, virtual destructors
Assignment-compatible, overloading of constructors, initialization list of constructors
See Code:
#include <iostream>using namespace Std;class base{public:base (): M (1), n (m+1) {Display (); When a virtual function is called in the constructor, its own virtual function base (int x,int y): M (x), n (y) {}void setxy (int x,int y) {m=x+1;n=y+1;} virtual void Display () {cout<< "m*n=" << M*n<<endl;} void Fun () {cout<< "member function accesses virtual function:";D isplay ();} Virtual ~base () {cout<< "destructor Base" <<ENDL;} Private:int m;int N;}; Class Subclass:public Base{public:subclass (int x,int y,int R1): Base (x, y), R (R1) {Display ();} Inheritance constructor void setxyr (int x,int y,int r) {setxy (x, y); r=r;} Inherited member function void Display () {cout<< "Sub--->" <<r*r<< ","; Base::D isplay ();} ~subclass () {cout<< "destructor subclass" <<ENDL;} Private:int R;}; void print (Base & P) {cout<< "external functions use references to call virtual functions:";p. Display (); void Print2 (Base *p) {cout<< "External function uses pointers to call virtual functions:";p->display ();} int main () {Base *bp; Subclass *SP; Base B1; Constructor base B (3,4); constructors, with virtual functions bp = &b; Subclass S (3,4,2); constructor, with virtual function sp = &s;b1.setxy (7,8); S.setxy (4,5); s.setxyr (4,5,2); b1 = s; FuThe value is compatible with BP = SP; Print (B1); A virtual function in an external function that points to the definition object print (s);p Rint2 (BP);p Rint2 (SP); B1.fun (); The member function accesses the virtual function s.fun (); B1. Display (); B.display (); S.display ();d elete BP; A virtual destructor, which points to a pointer to the base class, invokes the appropriate destructor, calling the derived class system ("pause") first;
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
An example shows the virtual function