Yesterday, when the written test encountered a very interesting topic, the general following:
Class parent{public: parent () { doit (); } ~parent () { doit (); } virtual void doit () { cout << "I ' m parent!" << endl; }};class Child: public Parent{public: child () { } ~child () { } void doit () { parent::d oit (); cout << "I ' m child!" << endl; }}; Int main () { parent *p_base = new child (); p_base->doit (); delete p_base; return 0;}
The case of calling virtual functions in a constructor was not previously written in the project, which is generally not allowed, increasing the complexity of the code (see effective C + + clause 9). Remember that the order of construction and destruction in C + + inheritance is not difficult to write the answer to:
I ' m parent! I ' m parent! I ' m child! I ' m parent!
But I think the topic should be more ingenious:
Class parent{public: parent () { doit (); } ~parent () { doit (); } virtual void doit () { cout << "I ' m parent!" << endl; }};class Child: public Parent{public: child () { doit (); } ~child () { doit (); } void doit () { parent::d oit (); cout << "I ' m child!" << endl; }};int main () { parent *p_ Base = new child (); p_base->doit (); delete p_base; return 0;}
If you write down:
I ' m parent! I ' m parent! I ' m child! I ' m parent! I ' m child! I ' m parent! I ' m child! I ' m parent!
Well, congratulations, you answered the wrong question. Because this topic does not call a subclass destructor at all, why? Because the destructor of the parent class is a non-virtual function, the static type that is disposed in the main function points to the parent class, so it does not call the destructor of the subclass at all. This is why in the inheritance system it is generally necessary to set the destructor of the parent class to a virtual function (see effective C + + clause 7), otherwise it is possible to cause a memory leak.
The correct answer is:
I ' m parent! I ' m parent! I ' m child! I ' m parent! I ' m child! I ' m parent! I ' m child! I ' m parent!
This article is from the "neverstop" blog, make sure to keep this source http://jlnsqt.blog.51cto.com/2212965/1616380
Constructor, destructor call virtual function