5

I'm really confused about these rules:

void func(float f)
{

}

struct Foo
{
    Foo(float b) {}
};
int main()
{

    short b = 1;
    
    func(b);/* WORKS FINE*/

    Foo foo{ b }; /*REQUIRES NARROWING CONVERSION FROM SHORT TO FLOAT */
    Foo foo2{ (short)b }; /* REQUIRES NARROWING CONVERSION FROM SHORT TO FLOAT */
    Foo foo3{ (short)7 }; /* WORKS FINE */
}

My first question, why can I call func(float) with an l-value of a short, but not use it as an argument to the constructor?

My second question is, even if we look at the passing of a short to the constructor, then it doesn't complain when we hand it an r-value short. Why is this the case?

Zebrafish
  • 11,682
  • 3
  • 43
  • 119
  • TL;DR of the dupes: implicit initialization narrowing is allowed, direct list initialization narrowing is an error. – NathanOliver Jan 24 '23 at 13:17
  • @NathanOliver I asked one of the dupes. What I'm doing is a simple constructor call with { }. It's only brace initialisation insofar as I use { } instead of ( ) for the constructor call. There's no initialiser list involved, the class has no constructor taking an initialiser list. "direct list initialization narrowing is an error." It's not direct list initialisation though, what do you mean by that? It's a simple constructor call in my case. – Zebrafish Jan 25 '23 at 07:15
  • Any use of constructing an object with `{}` is called list initialization: https://timsong-cpp.github.io/cppwp/dcl.init#general-16.1 – NathanOliver Jan 25 '23 at 13:15

0 Answers0