Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are explicitly declared destructors needed in the derived classes?

Consider the following code snippet:

class A
{
virtual void function();
public:
  virtual ~A() {};
}

class B: public A
{
virtual void function() override final;
public:
  /*virtual*/ ~B() {}; // does this d-tor have to be declared at all?
}

I can find the info regarding the base class destructor easily, e.g. http://en.cppreference.com/w/cpp/language/destructor

"Deleting an object through pointer to base invokes undefined behavior unless the destructor in the base class is virtual. A common guideline is that a destructor for a base class must be either public and virtual or protected and nonvirtual"

A virtual destructor in a base class is a must, how about the derived class's destructors, do they have to be explicitly declared/defined? I find it quite confusing, since the destructors of the derived classes are automatically virtual too. Is it legal in terms of vtable addressing to skip the derived class's destructor's declaration/definition? What about the following situation:

class A
{
virtual void function();
public:
  virtual ~A() {};
}

class B: public A
{
virtual void function() override;
public:
  /*virtual*/ ~B() {}; // does this d-tor have to be declared at all?
}

class C: public B
{
virtual void function() override final;
public:
  /*virtual*/ ~C() {};  // does this d-tor have to be declared at all?
}
like image 615
AdR Avatar asked Dec 25 '22 13:12

AdR


2 Answers

There is no need to define explicitly destructors in derived classes. According to the C++ Standard

If a class has a base class with a virtual destructor, its destructor (whether user- or implicitly-declared) is virtual

Also if you bother about the access control then

An implicitly declared destructor is an inline public member of its class.

The compiler will place the address of its implicitly defined destructor in vtable. So vtable for derived classes will store addresses of destructors of derived classes.

For readability of your code you could write for example

class B: public A
{
virtual void function() override final;
public:
  virtual ~B() = default;
}
like image 182
Vlad from Moscow Avatar answered Mar 30 '23 00:03

Vlad from Moscow


No, it does not need to be declared; classes that inherit from classes with a given function declared to be virtual do not need to declare their inherited form to be virtual for it to be virtual. This includes destructors which are implicitly declared.

like image 21
user3308105 Avatar answered Mar 30 '23 00:03

user3308105