Can I call virtual functions in constructors and destructors? __ function

Source: Internet
Author: User

You can, but do not achieve the desired effect, you should avoid calling virtual functions in constructors and destructors as much as possible.


Class base{public
:
    base () {
        cout<<the the size is size () <<endl; 
   }
Private:
    virtual size_t size () {return
        sizeof (*this);
    }
;

Class Derived:public class base{public
:
    derived () {
        cout<<the the size of is size () <<endl;
private:
    size_t size () {return
        sizeof (*this);
    }
;

When you define a derived instance object, calling size () in the constructor of base is Base::size () instead of derived::size () by static resolution.

It can be understood that when the base part is constructed, the derived is not a complete instance object, and the member variable of the derived part is not even initialized, if the virtual function of derived is invoked during the construction of base and the virtual function references a member variable that has not been constructed. Imagine what would happen. Therefore, in terms of security considerations, a virtual function is called by the object in the construct, and its function is the owning function of the object being constructed.


The same is true for destructors as well. When the base part is being refactored, the derived part has been destructor, the member variable is invalid, and the calling virtual function is the base.


Let's explain how the compiler does it.


Virtual function calls are related to virtual pointers to instance objects and to virtual tables of classes. Therefore, to control the invocation of a virtual function, you must control the initialization of the virtual pointer. So when an instance object is constructing the base part, the virtual pointer of the instance must point to the virtual table of the base class. Then when the virtual pointer is initialized, before the code written by the programmer or in the constructor initializes the members listed in the member list.



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.