std::has_virtual_destructor in C++ with examples

In this article, we will learn about the has_virtual_destructor in C++ with examples. This function of C++ STL tells us if any template type T has a virtual destructor or not.

Header File:

#include<type_traits>

Syntax:

template<class T>
struct has_virtual_destructor;

Parameter:

It can take only one parameter  T to check whether it has a virtual destructor or not.

Return Value:

  • If the virtual destructor is present, then true.
  • If not, then false.

Program to understand the has_virtual_destructor function in C++

Program 1:

#include<bits/stdc++.h>
using namespace std;
struct s1
{
    virtual ~s1() {}
};
struct s2
{

};
struct s3:s1
{

};

int main()
{
    cout << boolalpha;
    cout << "has_virtual_destructor:"
         << endl;
    cout << "int: "
         << has_virtual_destructor<int>::value
         << endl;
    cout << "s1: "
         << has_virtual_destructor<s1>::value
         << endl;
    cout << "s2: "
         << has_virtual_destructor<s2>::value
         << endl;
    cout << "s3: "
         << has_virtual_destructor<s3>::value
         << endl;
}

Output:

has_virtual_destructor:
int: false
s1: true
s2: false
s3: true

Program 2:

#include<bits/stdc++.h>
using namespace std;
struct s1
{

};
struct s2
{
    virtual ~s2() {}
};
struct s3:s2
{

};

int main()
{
    cout << boolalpha;
    cout << "has_virtual_destructor:"
         << endl;
    cout << "int: "
         << has_virtual_destructor<int>::value
         << endl;
    cout << "s1: "
         << has_virtual_destructor<s1>::value
         << endl;
    cout << "s2: "
         << has_virtual_destructor<s2>::value
         << endl;
    cout << "s3: "
         << has_virtual_destructor<s3>::value
         << endl;
}

Output:

has_virtual_destructor:
int: false
s1: false
s2: true
s3: true

Thank You for reading!!

Leave a Reply

Your email address will not be published. Required fields are marked *