The topic of this article is that the constructor cannot be a virtual function. First, you do not need to use your mind to remember it, because when you write a virtual constructor, the compiler can check it. The purpose of this article is why constructor cannot be a virtual function.
First, let's take a look at a piece of wrong code. The following code does not pass through the compilation phase.
1 class A {2 public: 3 Virtual A () {4 This-> value = 0; 5} 6 private: 7 int value; 8 };
Why cannot constructors be virtual functions? Here you need to know a concept, that is, virtual function table vtbl. Each class with virtual member functions has a pointer to the virtual function table. Objects use the virtual function address stored in the virtual function table to call virtual functions.
When is the virtual function table pointer initialized? Of course, it is a constructor. When we create an object through new, the first step is to apply for the required memory, and the second step is to call the constructor. Imagine that if the constructor is a virtual function, you must use vtbl to find the entry address of the virtual constructor. Obviously, the memory we applied for has not been initialized, and vtbl is not available. Therefore, the constructor cannot be a virtual function.