c++ - 析构函数和构造函数
大家讲道理
大家讲道理 2017-04-17 12:01:40
0
2
513

请大神解释下为什么通常析构函数有virtual,而构造函数为什么不能是virtual,最好结合例子说明下作用,O(∩_∩)O谢谢

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(2)
刘奇

I don’t want to write anymore, I’ll find two posts for you

  • Why the constructor cannot be a virtual function
  • The role of virtual destructor in C++
Ty80

First assume that you know the role of virtual functions. .

Every time you call the constructor, you and the compiler will clearly know the data type to be constructed, and then the base class constructor will be called again in the constructor

When calling the destructor, if the current pointer is a base class pointer, then you and the compiler will not be able to tell whether the space pointed by the pointer is a base class object or a derived class. At this time, the runtime needs to Check in the virtual function table which destructor needs to be called

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template