Recently I saw some code use the explicit
keyword in the constructor. To explain the explicit
, see the sample code here.
class Enemy {
public:
Enemy(int hp) : hp(hp) {} // implicit constructor
Enemy(int hp, int damage) : hp(hp), damage(damage) {}
int hp;
int damage;
};
class Player {
public:
explicit Player(int hp) : hp(hp) {} // explicit constructor
explicit Player(int hp, int damage) : hp(hp), damage(damage) {}
int hp;
int damage;
};
int main() {
Enemy a1 = 1000; // OK copy-initialization selects Player(int hp)
Enemy a2 = { 1000, 200 }; // OK
Enemy a3 = Enemy(1000); // OK
Enemy a4 = Enemy(1000, 200); // OK
Enemy a5 = (Enemy)1; // OK
Player b1 = 1000; // error: no viable conversion from 'int' to 'Player'
Player b2 = { 1000, 200 }; // error: chosen constructor is explicit in copy-initialization
Player b3 = Player(1000); // OK
Player b4 = Player(1000, 200); // OK
Player b5 = (Player)1000; // OK
return 0;
}
### Explanation
When use the implicit constructor, it equals to create a temporary instance and copy the temporary instance to the final instance.
For the explicit constructor, you must do something like this:
Player b1(1000);
You could find more information from the c++ reference page.