SubSea SubSea - 2 months ago 11
C++ Question

Assignment initialization of a constructor

I am trying out different versions of calling the constructor, and I came up with this

#include<iostream>
#include<string>
using namespace std;
class game{

public:
float version;
string name;
game()
{
name = "game";
version = 1.0;
}
game(float v,string n)
{
version = v;
name = n;
}
game(float v)
{
version = v;
name="any";
}
};
int main()
{
game lol1(1.0,"league of legends"); //functional form
game lol2 = 2.0; //assignment form
game lol3{3.0,"league2"}; //uniform initialization
game *pt = &lol1;
cout<<pt->name<<endl;
return 0;
}


Every statement compiles, but if I write

game lol2 = 2.0,"league of legends2"; //code 2


I get an error:


expected unqualified-id before string constant


But the following code works fine:

game lol2 = {2.0,"league of legends2"}; //code 3


I am not getting what exactly the issue is with the second code. Any ideas?

Answer

What you call "assignment form" is a copy initialization.

It works as if a temporary object is constructed from a single argument specified as initializer, and is then passed to the class' copy constructor or move constructor.

So, the code

game lol2 = 2.0,"league of legends2"; //code 2

… is just syntactically invalid.


Tip: Instead of three constructors, where the second adds a first argument, and the third adds a second argument, you can just use default argument values:

class game{

public:
    float version;
    string name;
    game(float v = 1.0,string n = "game")
        : version( v ), name( n )
    {}
};

The : syntax is a constructor member initializer list.

It can sometimes be more efficient, sometimes necessary, and anyway is usually more concise and conventional.