Direct initialization gives an error when initializing class types

90 views Asked by At
 struct Alien {
    int id;
    char const* name;
    Alien() = default;
    Alien(int id, char const* name) : id{id}, name{name} {}
    Alien(int id): id{id} {}
 };

 struct Spaceship {
    Alien alien1;
    Spaceship() = default;
    Spaceship(Alien const& z) {}
    Spaceship(Spaceship const& other) = default;
    Spaceship(Spaceship&& other) = default;
};

int main()
{
   Spaceship s1(3433); // works
   Spaceship s2(2322, "Kronas"); // error
}

source>:55:14: error: no matching constructor for initialization of 'Spaceship'
   Spaceship s(2322, "Kronas");
             ^ ~~~~~~~~
<source>:45:5: note: candidate constructor not viable: requires single argument 'z', but 2 arguments were provided
    Spaceship(Alien const& z) { }
    ^
<source>:46:5: note: candidate constructor not viable: requires single argument 'other', but 2 arguments were provided
    Spaceship(Spaceship const& other) = default;
    ^
<source>:47:5: note: candidate constructor not viable: requires single argument 'other', but 2 arguments were provided
    Spaceship(Spaceship&& other) = default;
    ^
<source>:44:5: note: candidate constructor not viable: requires 0 arguments, but 2 were provided
    Spaceship() = default;
    ^
1 error generated.
Execution build compiler returned: 1

The std says that in direct initialization an implicit conversion to one of the T argument's constructor is applicable. Why the second initialization with two arguments throws an error?

1

There are 1 answers

4
Ofiec On

None of Spaceship constructors accepts two arguments. That is why it throws an error when you give it two. There should be something like:

 Spaceship(int number, char const* name){
   alien1.id = number;
   alien1.name = name;
};