Do not call virtual functions in constructors and destructors

Source: Internet
Author: User

The reference to constructors and destructors must be well understood, but can you call virtual functions in constructors or destructors?

The answer is never to do this, and it won't get the results you want.

First, mention the constructor, the order of the constructors is to construct the-> subclass from the base class, if the virtual function is invoked in the base class, because the constructor base class has only its own

(or its parent, if present), is not invoked according to the rules of the virtual function table. See the following example

Class Base {

Public

Base () {callvirtual ();}

Protected

Virtual Callvirtual () {fprintf (stdout, base::callvirtual () \ n);}

};


Class Derived:public Base {

Public

Derived () {}

Protected

Virtual Callvirtual () {fprintf (stdout, derived::callvirtual () \ n);}

};


int main () {

Derived D;

}

The result is base::callvirtual (), because a derived class has not been constructed during the base class construction, and the functions of the derived class in the virtual function table are not joined

So when you look up a function, you can only find the call function of the base class


Similarly: Because the destructor of a subclass has already been invoked in a destructor, the virtual function table of a subclass cannot be accessed in the destructor of a parent class


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.