What is the use of virtual function and virtual destructor in C++
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