C + + notes (ii)--Do not call virtual functions in constructs and destructors

Source: Internet
Author: User

Ilocker: Focus on Android Security (novice) qq:2597294287

1 classTransaction {//base class for all transactions2  Public:3 Transaction ();4     Virtual voidLogtransaction ()Const=0;//make a different type of log record5 ... ..6 }7 transaction::transaction () {8 ... ..9 logtransaction ();Ten}

Derived class:

1 classBuytransaction: PublicTransaction {2  Public:3     Virtual voidLogtransaction ()Const;4 ... ..5 }6 classSelltransaction: PublicTransaction {7  Public:8     Virtual voidLogtransaction ()Const;9 ... ..Ten}

Now execute:

1 buytransaction b;

The base class part of the derived class object is first constructed, so the Transaction constructor is called first. The logtransaction that is called in the Transaction constructor is the version of Transaction, not the version of Buytransaction, even if the object type being created is buytransaction.

During the base class construct, the virtual function will never descend to the drived classes hierarchy, because the member variable of drived class is not initialized yet, and if the virtual function accesses an uninitialized member variable, it will result in ambiguous behavior, C + + forbid This dangerous operation.

More specifically: During the base class construction of the derived class object, the object type is the base class, not the derived class, which is also valid for RTTI (such as dynamic_cast, typeID).

In the same way, when the destructor of the base class is executed, the destructor of the derived class is executed, the member variables of the derived class render undefined values, and C + + sees them as non-existent, when the object is a base class object.

In the example, the constructor calls the virtual function directly, and you should also note that the constructor and destructor have no indirect calls to the virtual function.

Learning materials: "Effective C + +"

C + + notes (ii)--Do not call virtual functions in constructs 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.