When we use the C ++ programming language for program development, we will gradually find that this language has brought great benefits to our program development. We know that C ++ fictitious functions used for base classes during C ++ development are generally virtual functions. But why? Here is a small example:
There are two classes:
- class ClxBase
- {
- public:
- ClxBase() {};
- virtual ~ClxBase() {};
- virtual void DoSomething() { cout << "Do something
in class ClxBase!" << endl; };
- };
- class ClxDerived : public ClxBase
- {
- public:
- ClxDerived() {};
- ~ClxDerived() { cout << "Output from the destructor
of class ClxDerived!" << endl; };
- void DoSomething() { cout << "Do something
in class ClxDerived!" << endl; };
- };
Code
- ClxBase *pTest = new ClxDerived;
- pTest->DoSomething();
- delete pTest;
The output result is:
- Do something in class ClxDerived!
- Output from the destructor of class ClxDerived!
This is very easy to understand.
However, if you remove the virtual before the ClxBase destructor, the output result is as follows:
- Do something in class ClxDerived!
- Summary of the Application Experience of C ++ traversal set
- Detailed description of C ++ assignment function code
- Analysis of C ++ variable declaration concepts
- Detailed description of how C ++ implements WPF Animation
- Detailed description of C ++ Chinese character-related application methods
That is to say, the destructor of the class ClxDerived is not called at all! Under normal circumstances, all the class destructor release the memory resources, and if the Destructor is not called, memory leakage will occur. I think all C ++ programmers know this danger. Of course, if you do other work in C ++ fictitious functions, all your efforts will be wasted.
Therefore, the answer to the question at the beginning of the article is -- This is to call the destructor of a derived class when a base class pointer is used to delete an object of A derived class.
Of course, it is not necessary to write all class destructor as virtual functions. When there is a virtual function in the class, the compiler will add a virtual function table to the class to store the virtual function pointer, which will increase the storage space of the class. Therefore, C ++ fictitious functions are written as virtual functions only when a class is used as the base class.