Virtual functions are never called in constructor and destructor.

Source: Internet
Author: User

Take a look at the following code and ask whether print calls the base class or the version of the derived class?


The answer is the base class...
Maybe everyone will be surprised. Isn't print a virtual function? Why not call the version of the derived class? First, when defining an object of A derived classThe execution of base class constructor is earlier than that of derived class.Constructor,Therefore, when the base class constructor calls this function, the member of the derived class has not yet been initialized (Note: The real virtual function table has not been fully initialized at this time ).If the function of the derived class is called at this time (the uninitialized member may be used), it will be troublesome. Therefore, C ++ prohibits you from doing so ..
In fact,During the base class construction of the derived class object, the object type is Bass class rather than derived class.Therefore, virtual function calls must be the base class version ..


The same principle applies to destructor.

As you know, the sequence of calling the Destructor is the opposite of that of the constructor when the object of the derived class is destructed:

The destructor of a derived class is prior to the destructor of the base class.

Therefore, in the process of calling the base destructor, the compiler regards it as a base class object ..

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.