The constructor cannot be a virtual function. When you create a derived class object, the constructor of the derived class is called instead of the constructor of the base class, and then the constructor of the derived class uses a constructor of the base class, which differs from the inheritance mechanism.
Therefore, a derived class does not inherit the constructor of a base class, so declaring a class constructor as a virtual function is meaningless.
The destructor should be a virtual function, unless the class does not use the base class.
The default is called "Static binder."
//HeritedDerived.cpp:Defines the entry point for the console application.//#include"stdafx.h"#include"stdio.h"#include<iostream>using namespacestd;classfather{ Public: Father () {cout<<"I am father!\n"; } Virtual~Father () {cout<<"This is father ' s destructor!\n"; Compare (); } Virtual voidOutput () {cout<<"This was a debug function in father\n"; } Virtual voidCompare () {cout<<"This was another virtual function in father\n"; } };classSon: Publicfather{ Public: Son () {cout<<"I am son!\n"; M_pint=New int[ +]; } ~Son () {cout<<"This is son ' s destructor!\n"; if(NULL! =m_pint) { Delete[] m_pint; M_pint=NULL; cout<<"Memory Release successfully!\n"; } Compare (); } Virtual voidOutput () {cout<<"This was a debug function in son\n"; } Virtual voidCompare () {cout<<"This was another virtual function in son\n"; }Private: int*M_pint;};int_tmain (intARGC, _tchar*argv[]) {Father Father; Son son; Son. Output (); Father*father1 =NewSon; Father1-Output (); DeleteFather1; return 0;}
}
You should typically provide a virtual destructor to the base class, even if it does not require a destructor.
Constructors and destructors cannot invoke other virtual functions, even if they are called, they lose the meaning of virtual functions. The object dynamic generation mechanism of C + +.
virtual function (constructor + destructor)