I read one book and ran into such a code:
class command
{
Public:
Virtual ~ COMMAND () {}
Virtual Void Execute (GameActor & Amp; Actor) = 0;
};
Explain why you need a virtual destructor? If I do not write it, then there will be any problems?
Answer 1, Authority 100%
The virtual destructor is necessary to avoid possible resource leaks or other uncontrolled object behavior, in which the destructor call is included.
# include & lt; iostream & gt;
Using Namespace STD;
Struct Base.
{
Base () {cout & lt; & lt; "Base ()" & lt; & lt; Endl; }
~ Base () {cout & lt; & lt; "~ BASE ()" & lt; & lt; Endl; }
};
Struct Derived: Public Base
{
Derived () {cout & lt; & lt; "Derived ()" & lt; & lt; Endl; }
~ Derived () {cout & lt; & lt; "~ Derived ()" & lt; & lt; Endl; }
};
INT MAIN ()
{
Base * OBJ = new DERIED ();
Delete OBJ;
}
What could you expect at the exit:
base ()
DERIVED ()
~ Derived ()
~ Base ()
What can happen (maybe because, in general, it is Undefined Behaviour ):
base ()
DERIVED ()
~ Base ()
To eliminate this problem, a parent class destructor is needed to announce virtual (Virtual ~ Base ()
), which will allow the compiler to get to the destructor of the heir on the virtual feature table.