Specifies that a constructor or cast function (since C++ 11) is explicit, that is, it cannot be used for implicit casts and copy initialization.
Let’s take an example, you have the following code:
The
do_something
function takes a parameter of typeTerminalRoot
, but the compiler automatically converts it toint
:
#include <iostream>
class TerminalRoot {
public:
TerminalRoot( int num ) : m_var( num ){}
int get_var(){
return m_var;
}
private:
int m_var;
};
void do_something( TerminalRoot terroo ){
int x = terroo.get_var();
std::cout << "Type is: " << typeid( x ).name() << '\n';
}
int main(){
do_something( 963 );
return 0;
}
And you don’t want that, you want the correct type to be passed, because you want to know if there is a bug in that type. So you use the explicit
keyword, but when compiling there is an error compiling:
#include <iostream>
class TerminalRoot {
public:
explicit TerminalRoot( int num ) : m_var( num ){}
int get_var(){
return m_var;
}
private:
int m_var;
};
void do_something( TerminalRoot terroo ){
int x = terroo.get_var();
std::cout << "Type is: " << typeid( x ).name() << '\n';
}
int main(){
do_something( 963 );
return 0;
}
And then you get the error:
error: could not convert ‘963’ from ‘int’ to ‘TerminalRoot’
Cannot convert int
to TerminalRoot
. So you need to pass the correct type now: do_something( TerminalRoot( 963 ) );
#include <iostream>
class TerminalRoot {
public:
explicit TerminalRoot( int num ) : m_var( num ){}
int get_var(){
return m_var;
}
private:
int m_var;
};
void do_something( TerminalRoot terroo ){
int x = terroo.get_var();
std::cout << "Type is: " << typeid( x ).name() << '\n';
}
int main(){
do_something( TerminalRoot( 963 ) );
return 0;
}
The output is i
( from int
), but you have passed the correct type and verified that it is working . For more information see the link: https://en.cppreference.com/w/cpp/language/explicit .
That’s all for today, small daily doses that will always keep us in tune with C++!