Original: http://blog.csdn.net/xhz1234/article/details/6510568
C + +: Can constructors and destructors be virtual functions?
The simple answer is that the constructor cannot be a virtual function, and the destructor can and often is a virtual function.
(1) The constructor cannot be a virtual function
Let's take a look at Daniel C + + 's father Bjarne Stroustrup in "the C + + programming Language" in what it says:
To construct an object, a constructor needs the exact type of the object it was to create. Consequently, a constructor cannot be virtual. Furthermore, a constructor is isn't quite an ordinary function, in particular, it interacts with memory management in ways O Rdinary member functions don ' t. Consequently, you cannot has a ponter to a constructor.
--- from "the C + + progamming Language" 15.6.2
Daniel, however, is too difficult to understand for the average person. Then try to explain why:
This involves the construction of C + + objects, C + + objects are constructed in three places: (1) function stacks, (2) free storage, or heap, (3) static storage. No matter where it is built, the process is two steps: First, allocate a piece of memory, and second, call the constructor. Well, the problem is, if the constructor is a virtual function, then it needs to be called through vtable , but at this time facing a raw memeory, where to find vtable ? After all,vtable is initialized in the constructor, not before it. Therefore, the constructor cannot be a virtual function.
(2) Destructors can be virtual functions and are often so
This is good to understand, because at this point the vtable has been initialized, and we usually destroy the object by a pointer to the base class, and if the destructor is not virtual, the object type cannot be correctly identified and the object cannot be destroyed correctly.
What confuses us is that we often see the term "Fictional creation function," which is blamed on irresponsible or fraught media (including books, technical articles, etc.). Because they're talking about something like the following:
Class Expr {
Public
Expr ();
Expr (const expr&);
Virtual expr* new_expr () {return new Expr ();}
Virtual expr* Clone () {return new Expr (*this);}
};
---turn from Linux Tour
C + +: Constructors and destructors can be virtual functions