Virtual function from official explanation is:
A virtual function is a member function that you expect to be redefined in derived classes. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the function.
Please see the code first:
#include<iostream>
using namespace std;
class A
{
public:
A(){cout << "A()" << endl;}
~A(){cout << "~A()" << endl;}
};
class B:public A
{
public:
B(): A(){cout << "B()" << endl;}
~B(){cout << "~B()" << endl;}
};
int main()
{
A * pt = new B;
delete pt;
}
Output is:
A()
B()
~A()
My question is:
- Destructor of base class can't be inherited by derived class, so why we make destructor of base class to be virtual?
- For the code above, I know this will lead to problem(here destructor of class B not called). I have searched so many articles or questions from google and stackoverflow and all of them tell me that destructor of base should be virtual but how "virtual" on destructor works? I mean that what the difference in core code level with/without "virtual" to the destructor?