Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the use of virtual function and virtual destructor in C++

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces the use of virtual functions and virtual destructors in C++. It has a certain reference value. Interested friends can refer to it. I hope you will gain a lot after reading this article. Let the editor take you to know it.

Virtual function and virtual destructing function

There are two distinct member functions in the class, the constructor and the destructor. What happens to the health of constructors and destructors when they encounter inheritance and polymorphism?

Polymorphism is the most appropriate member function to execute in a parent class or subclass. In general, only one member function in the parent or subclass is selected to execute. This brings trouble to the destructor! If some resources are requested by the constructor of the parent class, some resources are requested by the constructor of the subclass, and the virtual function only allows the program to execute a destructor in the parent class or subclass, isn't it destined that some resources will not be released? In order to solve this problem, the virtual destructor becomes different.

Let's add the reserved word virtual to the front of the destructor and see what happens when it runs:

/ / animal.h

# include

Using namespace std

Class Animal

{

Public:

Animal (int w = 0, int a = 0)

Virtual ~ Animal ()

Protected:

Int weight

Int age

}

Animal::Animal (int w, int a)

: weight (w), age (a)

{

Cout

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report