LoginSignup
0
0

More than 5 years have passed since last update.

[C++] explicit & converting constructor

Last updated at Posted at 2016-04-14

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.

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0