Open In App

std::is_base_of template in C++ with Examples

Last Updated : 12 Jun, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • class A(as a Base class): It represents the base class.
  • class B(as a Derived class): It represents the derived class.

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

  • True: If the Base class(class A) is the parent of the Derived class(class B).
  • False: If the Base class(class A) is not the parent of the Derived class(class B).

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/



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads