No Virtual constructors but virtual destructor

前端 未结 3 566
隐瞒了意图╮
隐瞒了意图╮ 2021-02-06 17:19

If we dont have virtual constructors then why we have virtual destructors? Can constructors also be virtual?

3条回答
  •  太阳男子
    2021-02-06 17:52

    • There is no point in virtual constructor - you declare exactly what type is created, and it is well known in compile time. The compiler do not need [and actually cannot, since the dynamic dispatch is based on information which is created only after the object was created]. So there are no virtual constructors.
    • Virtual destructors are important to prevent memory leaks, and monitor the system. Assume you have A* a = new B; [B inherits from A], and you later delete a; - the compiler has no way of knowing a is a B [in the general case], and will invoke A's destructor - if it wasn't virtual, and you might get a memory leak, or other faults.
    • Using virtual destructor - you ensure that B's destructor is invoked, since a B object is being destroyed.

提交回复
热议问题