Home c++ Why do you need a virtual destructor?

Why do you need a virtual destructor? [Duplicate]

Author

Date

Category

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.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions