C++ Review Road Fifteen - Virtual Destructor

I reviewed virtual functions before, and today I will review virtual destructors.

A virtual destructor is also a destructor, it also has no return value and no parameters . It's called a virtual destructor because a virtual keyword is added before the normal destructor.

The role of virtual destructors

We first define such a class A, and then class B inherits it, declares a pointer in both classes, allocates memory space to them in the constructor, and makes them point to a class containing ten chars An array of data of type.

class A
{
public:
	A()
	{	cout << "A()" << endl;
		p = new char[10];
	}
	~A()
	{
		cout << "~A()" << endl;
		delete [] p;
	}

private:
	char *p;
};

class B : public A
{
public:
	B()
	{
		cout << "B()" << endl;
		pb = new char[10];
	
	}
	~B()
	{
		cout << "~B()" << endl;
		delete [] pb;
	}
private:
	char * pb;	
};

In the main function, we declare a pointer of type A to point to an object of class B:

A *b = new B;

In this way, the object of class B will automatically call its constructor. The order of calling the constructor is to call from the base class, and then to its derived class. After the work of this pointer object is done, we will use delete to let it release resources. At this time, we hope that all resources in the base class and derived class will be recycled, but the fact is often different from what we think. difference.

If we use delete b, we will get this result:

A()
B()
~A()

Obviously this is not the result we want. The polymorphism we reviewed before is very similar to this situation. At this time, we want to release all the resources of the derived class and the base class, but now only the resources of the base class are released. So we add virtual to turn the base class's mechanism function into a virtual destructor.

class A
{
public:
	A()
	{	cout << "A()" << endl;
		p = new char[10];
	}
	virtual ~A()
	{
		cout << "~A()" << endl;
		delete [] p;
	}

private:
	char *p;
};

Then we execute the above statement again, and the result we want will appear at this time.

A()
B()
~B()
~A()

Note the order in which constructors and destructors are called, the order in which fictitious functions are called and the order in which constructors are called is reversed. In this way, we have successfully reclaimed the resources of the base class and its derived classes.

Summarize

If we want to recycle the resources of the base class and all its derived classes through the pointer of the base class, that is, to execute both the destructor of it and its derived classes, we need to add a fictitious function before the base class. virtual makes it a virtual destructor.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325948761&siteId=291194637