Open In App

std::is_base_of template in C++ with Examples

The std::is_base_of template of C++ STL is present in the <type_traits> header file. The std::is_base_of template of C++ STL is used to check whether class Base is the base class of Derived class or not. It return the boolean value true or false on the basis of above condition.

Header File:



#include<type_traits>

Template Class:

template <class Base, class Derived>
struct is_base_of;

Syntax:



std::is_base_of<A, B>::value

Parameters: It accepts the below two classes as a parameters:

Return Value: This template returns a boolean variable as shown below:

Below is the program to illustrates the std::is_base_of template in C/C++:

Program 1:




// C++ program to demonstrate the
// std::is_base_of templates
#include <bits/stdc++.h>
#include <type_traits>
using namespace std;
  
// Base class A
class A {
};
  
// Derived Class B
class B : A {
};
  
// Class C
class C {
};
  
// Driver Code
int main()
{
  
    cout << boolalpha;
  
    // Check if class A is a base class
    // of class B
    cout << "A is base class of B: "
         << is_base_of<A, B>::value
         << endl;
  
    // Check if class B is a base class
    // of class A
    cout << "B is base class of A: "
         << is_base_of<B, A>::value
         << endl;
  
    // Check if class C is a base class
    // of class B
    cout << "C is base class of B: "
         << is_base_of<C, B>::value
         << endl;
  
    // Check if class C is a base class
    // of class C
    cout << "C is base class of C: "
         << is_base_of<C, C>::value
         << endl;
  
    return 0;
}

Output:
A is base class of B: true
B is base class of A: false
C is base class of B: false
C is base class of C: true

Reference: http://www.cplusplus.com/reference/type_traits/is_base_of/


Article Tags :
C++