Objective C ++ Study Notes-cla07: Declares virtual destructor for a polymorphism base class

Source: Internet
Author: User
Declare Destructors virtual in polymorphic base classes 1. Why declare a virtual function?In C ++ programming, a base class usually has multiple derived types, while most of the base classes are pure virtual functions, which require implementation of derived types. In this case, a base type pointer is returned by using the factory mode. In C ++, it is clearly pointed out that a derived type is deleted by a base type pointer, and the result of this base type carrying a non-virtual destructor is undefined. Only one local destruction occurs, that is, the base type resources are released, and the derived type causes memory
Leak, see the following code:
// Virtual_const.cpp: defines the entry point of the console application. // # Include "stdafx. H" # include <iostream> using namespace STD; class base {public: Base (){}~ Base () {cout <"~ Base () "<Endl ;}//// for the output result without virtual, see Figure 1 // virtual ~ Base () {cout <"~ Base () "<Endl ;}//// for details about the output result with virtual, see Figure 2}. Class derived: public base {public: derived () {P = (char *) malloc (sizeof (char) * 10 );}~ Derived () {free (p); cout <"~ Derived () "<Endl;} PRIVATE: char * P;}; int _ tmain (INT argc, _ tchar * argv []) {base * PTR = new derived (); If (PTR = NULL) {cout <"unallocated successfully" <Endl; exit (1);} Delete PTR; return 0 ;}
Figure 1: output results without virtual: Figure 2: output results with virtual:
The above code and output result show that the derived class inherits the base class, applies for memory resources on heap, and is released in its destructor. However, since the base destructor is non-virtual, the PTR pointer in the derived type is not correctly released. 2. Internal Mechanism of virtual functionsPolymorphic (with polymorphism) base classes should declare a virtual destructor. If the class has any virtual function, it should have a virtual destructor. Classes is designed
Virtual destructor should not be declared if classes is used or not to have polymorphism (polymorphically. So isn't it true that all classes are added with virtual destructor to keep them safe. Do not add virtual characters to the Destructor unless necessary. The reason is that virtual has a cost. To implement virtual functions, you must add a pointer in the class to point to the virtual function table, which increases the volume of the class. Do not declare virtual destructor unless necessary. The general rule is that destructor are declared as virtual only when virtual functions exist in the class. That is to say, this base class has a polymorphic. The implementation of a virtual function requires that its object contain additional information, which is used to determine which virtual function the object needs to call at runtime. Generally, this information takes the form of a pointer, which is called "vptr" ("virtual function table Pointer "). Vptr points to an array containing function pointers. This array is called "vtbl" ("virtual function table"). Each class containing virtual functions has a vtbl associated with it. When a virtual function is called by an object, the object's
Vtbl pointed to by vptr. Find a proper function pointer in vtbl and call the corresponding real function. See the following code to know that declaring a virtual function is a waste of system resources.

 

// Sev_vir.cpp: defines the entry point of the console application. // # Include "stdafx. H" # include <iostream> using namespace STD; Class class1 {}; class class2 {public: Virtual ~ Class2 () ;}; int _ tmain (INT argc, _ tchar * argv []) {cout <sizeof (class1) <Endl; cout <sizeof (class2) <Endl; return 0 ;}

3. Please note

But there is another problem, that is, inherit the classes of standard class libraries without virtual functions, such as the string class. If you inherit the string class, when you use the string pointer to release your inherited class, the problem described above still exists. Your inherited class does not release the space to be released. Because string does not have a virtual destructor. Therefore, do not inherit these classes without virtual destructor.

Also, containers in STL are meaningless because they do not provide virtual destructor either. C ++ does not provide constraint keywords such as final and sealed of Java or C # To prohibit inheritance of a type. Not all types are used for inheritance purposes, nor are they designed for Polymorphism purposes, so correct design is important.

4. Pure virtual function implementation

// Pure_vir.cpp: defines the entry point of the console application. // # Include "stdafx. H" # include <iostream> using namespace STD; class base // abstract class {public: Virtual ~ Base () {}; // virtual, not pure virtual void func () const = 0; // pure virtual}; void base: func () const // pure virtual also can have function body {cout <"base: func" <Endl;} class derived: public base {public: derived () {} virtual void func () const {base: func (); cout <"derived: func" <Endl ;}virtual void Foo (){}}; int _ tmain (INT argc, _ tchar * argv []) {base * pb = new derived (); Pb-> func (); Pb-> base :: func (); Return 0 ;}
From the generated results, we can see that the class with pure virtual functions is an abstract class. Objects cannot be generated and can only be derived.

If the pure virtual function of the derived class is not rewritten, its derived class is still an abstract class. The pure virtual function is defined to make the base class non-instantiated, because the instantiation of such abstract data structure itself does not make sense. Or the implementation is meaningless. In fact, I personally think the introduction of pure virtual functions is meaningless.,To ensure security, avoid any unknown results that need to be clarified but caused by carelessness, and remind the subclass to implement the implementation ..

Remember:

1. polymorphic (with polymorphism) base classes should declare a virtual destructor. If the class has any virtual function, it should have a virtual destructor.

2. classes should not be declared if it is not used as a base classes or for a polymorphically nature.

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.