Why do we need a virtual destructor with dynamic variables when we have inheritance? and what is the order for destructor execution in both the static/dynamic case? won't the destructor of the most derived class always execute first?

有帮助吗?

解决方案 2

Imagine you have this:

class A { 
  public:
  int* x;     
}
class B : public A {
  public:
  int *y;
}


main() {
  A *var = new B;
  delete var;
}

Please assume some constructors destructors. In this case when you delete A. If you have virtual destructors then the B destructor will be called first to free y, then A's to free x.

If it's not virtual it will just call A's destructor leaking y.

The issue is that the compiler can't know beforehand which destructor it should call. Imagine you have a if above that constructs A or B depending on some input and assings it to var. By making it virtual you make the compiler deffer the actual call until runtime. At runtime it will know which is the right destructor based on the vtable.

其他提示

You need a virtual destructor in the base class when you attempt to delete a derived-class object through a base-class pointer.

Case in pont:

class Foo
{
public:
  virtual ~Foo(){};
};

class Bar : public Foo
{
public:
  ~Bar() { std::cout << "Bye-Bye, Bar"; }
};

int main()
{
  Foo* f = new Bar;
  delete f;
}

Without the virtual destructor in the base class, Bar's destructor would not be called here.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top