為什麼要把父類的解構函式設定為virtual

為什麼要把父類的解構函式設定為virtual

如果我們想通過基類的指標去釋放子類的物件(這裡必須是new出來的物件),就需要基類將基類的虛擬函式設定為virtual,看下面的例子:

#include<iostream>
using namespace std;
class Parent
{
private:
int m_a;
public:
Parent(int a = 0)
{
this->m_a = a;
}
~Parent()
{
cout<<"parent destructor"<<endl;
}
};
class Child:public Parent
{
private:
int m_c;
public:
Child(int c = 0)
{
this->m_c = c;
}
~Child()
{
cout<<"child destructor"<<endl;
}
};
void del(Parent *base)//基類指標
{
delete base;
}
void main()
{
Parent *p_a = new Parent;
Child *c_a = new Child;
del(p_a);
del(c_a);
system("pause");
}

這裡寫圖片描述
發現在呼叫del函式進行空間釋放的時候,當傳入子類的物件時候,子類的物件的解構函式並沒有呼叫。要想通過基類的指標釋放通過子類物件,必須將父類(基類的)的解構函式設定為virtual。如下:

#include<iostream>
using namespace std;
class Parent
{
private:
int m_a;
public:
Parent(int a = 0)
{
this->m_a = a;
}
virtual ~Parent()
{
cout<<"parent destructor"<<endl;
}
};
class Child:public Parent
{
private:
int m_c;
public:
Child(int c = 0)
{
this->m_c = c;
}
~Child()
{
cout<<"child destructor"<<endl;
}
};
void del(Parent *base)//基類指標
{
delete base;
}
void main()
{
Parent *p_a = new Parent;
Child *c_a = new Child;
del(p_a);
del(c_a);
system("pause");
}

這裡寫圖片描述