开发者

Why do we have a virtual destructor and not a virtual constructor in c++?

开发者 https://www.devze.com 2023-04-12 19:47 出处:网络
Why can we have a virtual destructor but not virtual开发者_Go百科 constructor?The constructor chain can be determined at compile time, because you use new ClassName() always from the most specific cla

Why can we have a virtual destructor but not virtual开发者_Go百科 constructor?


The constructor chain can be determined at compile time, because you use new ClassName() always from the most specific class possible.

However you call destructors on possibly parent classes if you use polymorphism, so you can't know at compile time where to start the chain from. You need a virtual function to always call the right one (or you'd end up with potentially uncleaned resources in the most specific classes).

0

精彩评论

暂无评论...
验证码 换一张
取 消