Effective C + + Item 09-Never call the virtual function in constructors and destructors

Source: Internet
Author: User

Item 09-Never invoke virtual functions in constructors and destructors (never call virtual functions during construction or destruction)


Why?

Since the base class constructor executes earlier than the derived class constructor, the member variables of the base class constructor executing derived class have not been initialized. If the virtual function called during the period drops down to the derived class, it is necessary to know that the function of derived class will almost certainly take the local member variable, and those member variables have not been initialized. This can lead to ambiguous behavior.

Root cause: During the base class construction of the derived class object, the object's type is base class rather than derived class.

destructor Similarly, once the derived class destructor starts executing, the derived class member variables within the object do not render undefined values, so C + + sees them as if they do not exist. After entering the base class destructor, the object becomes a base class object, and any part of C + + includes the virtual function, dynamic_casts, and so on.


Please remember:

Do not call the virtual function during construction and destruction, because such calls never go down to derived class (compared to the layer that currently executes constructors and destructors).

Effective C + + Item 09-Never call the virtual function in constructors and destructors

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.