is_final template in C++



In this article we will be discussing the working, syntax and examples of std::is_final template in C++ STL.

is_final is a template which comes under the <type_traits> header file. This template is used to check whether the given type T is a final class or not.

What is a final class in C++?

When we declare a class with the final specifier then it is called as Final Class. Final class is a special kind of class which can’t be extended to create another class. In C++ to make a class as a final we make a class as a friend and then virtually inherit that class, to make that class nonextendable.

Example of a final class

class final_abc; //Class which is to be made final class abc {    private:    abc(){cout<<"abc constructor";}    friend class final_abc; }; class final_abc : virtual abc //made it final class. {    public:    final_abc(){cout<<"Final class constructor";} }; class derive : public final_abc; //Error can't be extended

Syntax

template <class T> is_final;

Parameters

The template can have only parameter of type T, and check whether the given type is a final class type or not.

Return value

It returns a Boolean value, true if the given type is a final class, and false if the given type is not a final class.

Example

Input: class final_abc;    class abc { friend class final_abc; };    class final_abc : virtual abc{ };    is_final<abc>::value; Output: False Input: class final_abc;    class abc    { friend class final_abc; };    class final_abc : virtual abc{ };    is_final<final_abc>::value; Output: True

Example

 Live Demo

#include <iostream> #include <type_traits> using namespace std; class TP {    //Same if it will be a structure instead of a class }; class T_P final {    //Same if it will be a structure instead of a class }; int main() {    cout << boolalpha;    cout << "Using is_final";    cout << "\nTutorials Point: "<<is_final<TP>::value;    cout << "\nT_P Final: "<<is_final<T_P>::value;    cout << "\ncheck for char: "<<is_final<int>::value;    return 0; }

Output

If we run the above code it will generate the following output −

Using is_final Tutorials Point: false T_P Final: true check for char: false

Example

 Live Demo

#include <iostream> #include <type_traits> using namespace std; union TP {    //Union }; union T_P final {    //Union }; int main() {    cout << boolalpha;    cout << "Using is_final";    cout << "\nTutorials Point: "<<is_final<TP>::value;    cout << "\nT_P Final: "<<is_final<T_P>::value;    cout << "\ncheck for char: "<<is_final<int>::value;    return 0; }

Output

If we run the above code it will generate the following output −

Using is_final Tutorials Point: false T_P Final: true check for char: false
Updated on: 2020-03-23T05:08:08+05:30

210 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements