Why cannot I declare a destructor as a virtual function? Why should I declare a destructor as a virtual function?

Source: Internet
Author: User

Is the virtual function table created at runtime or during compilation in polymorphism?

A: The virtual function table is determined during compilation, and the virtual function pointer vptr of class objects is determined in the runtime stage, which is the key to realizing polymorphism.

(The call of a class function is not determined at compilation, but determined at runtime, when writing code, you cannot determine whether the base class function or the derived class function is called. Therefore, it is declared as a virtual function. The virtual function and virtual function table are two different things. The virtual function is called at runtime, and the virtual function table is determined at compilation .)

 

Why cannot constructors be declared as virtual functions?

1. when creating an object, you must specify its type. Otherwise, it cannot be created. After an object is created successfully, the compiler obtains its actual type and then calls the corresponding function, if the constructor is declared as a virtual function, a deadlock will occur. The virtual function is running to determine which type of function it calls, which type is determined by the compiler based on the object type, but the actual type of the object cannot be known before it is created.

2. the virtual function corresponds to a virtual function table, which is stored in the object's memory space. If the constructor is a virtual function, it needs to be called through the virtual function table, however, the object has not been instantiated, that is, the memory space is not available, and the virtual function table cannot be found. Therefore, the constructor cannot be declared as a virtual function.

Why cannot I declare a destructor as a virtual function? Why should I declare a destructor as a virtual function?

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.