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?