13th read Program 2: Virtual destructor, 13th read

Source: Internet
Author: User

13th read Program 2: Virtual destructor, 13th read

Problem and code:

# Include <iostream> using namespace std; class BASE {private: char c; public: BASE (char n): c (n) {} virtual ~ BASE () // virtual destructor {cout <c ;}}; class DERIVED: public BASE {private: char c; public: DERIVED (char n ): BASE (n + 1), c (n) {}// the data member of the derived class is assigned a value of n BASE class data member and is set to n + 1 ~ DERIVED () {cout <c ;}}; int main () {DERIVED d ('x'); // Through the constructor, the data member of the DERIVED class c = X, base data member c = Y return 0 ;}

Running result:


Knowledge Point summary:
The declaration of virtual destructor adds virtual

If the destructor of the base class is not defined as a virtual destructor, the pointer of the base class does not execute the destructor of the derived class. Therefore, in a better project, the fictitious functions of the base class are defined as virtual destructor.

Of course, the program given by the instructor is the object of the created derived class and does not involve pointers. Therefore, even if you remove virtual, You can execute the fictitious functions of the derived class object.


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.