Converting constructor with multiple arguments

  • A+
Category:Languages

In C++11, a constructor without explicit keyword can be used to convert a list of arguments implicitly to its class. For example:

class Date{ private:   int d, m, y; public:   Date(int _d, int _m=0, int _y=0) : m(_m), d(_d), y(_y) {}   friend bool operator==(const Date &x, const Date &y) {return  x.d==y.d;} };  int main() {   Date x = {1,2,3}; // no error; using converting constructor   x == 1; // no error; converting constructor turns int into Date object   x == {1,2,3}; // error } 

For x == {1,2,3}, I got the following error:

explicit.cc:16:10: error: expected primary-expression before ‘{’ token        x=={1,2,3};           ^ 

I am wondering why converting constructor doesn't convert list {1,2,3} to Date object? Especially since x == 1 does not result in an error, why does x == {1,2,3}?

 


You might be especially surprised that:

x = {1, 2, 3};            // ok x == {1, 2, 3};           // error operator==(x, {1, 2, 3}); // ok 

This is because there are just specific places where a braced-init-list (basically, a comma-delimited list of stuff between {}s) is allowed to go in the language. It can go on the right-hand side of = because the rules say it can. It can be used as an argument in a function call expression because the rules say it can. But it cannot be used on either side of the comparison operators because the rules don't allow for it.

I do not know if there is a fundamental reason behind this beyond there probably not being a strong need for it.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: