Why do I have to make the Destructor virtual when defining a class?

Source: Internet
Author: User

In fact, this is a principle of effect c ++, but it is silly and stupid, always forget, write down the tunnel to remember.

 

I:

Class
{
Public:
~ A ()
{
Cout <_ function _ <Endl;
}
};

Class B: public
{
Public:
~ B ()
{
Cout <_ function _ <Endl;
}
};

Int _ tmain (INT argc, _ tchar * argv [])
{
A * P = new B; // when P is released, it is called only the destructor of A because it is of the type.

Delete P;

Return 0;
}

So the key to the problem is: when a subclass inherits from this parent class, and this parent class does not use a virtual destructor, this happens when a * P = new B is used. When P is parsed, the program only calls the destructor of Class, instead, I would never think of calling Class B.

 

II:

Class
{
Public:
Virtual ~ A ()
{
Cout <_ function _ <Endl;
}
};

Class B: public
{
Public:
Virtual ~ B ()
{
Cout <_ function _ <Endl; // a miracle occurred. After the subclass calls its own destructor, it will continue to automatically call the destructor of the parent class.
}
};

Int _ tmain (INT argc, _ tchar * argv [])
{
A * P = new B;

Delete P;

Return 0;
}

 

When the destructor of A is declared as virtual, The destructor of its subclass will overload it, even if
A * P = new B; in this case, no sub-class destructor is called.


 

Note:


Used

After the subclass calls its own destructor, it will continue to automatically call the destructor of the parent class.





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.