+ 1

Array argument with () and {}

Hi Refer code below: I have tried to give very basic reason of () and {} for array argument in below code: Would be interested to knowing very technical reason behind these two. https://sololearn.com/compiler-playground/cvC5nAvPrBV3/?ref=app

1st Sep 2024, 4:06 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
7 Respuestas
+ 1
I know I think how it works. Constructor is not marked explicit so implicit conversion happens from one argument due to last argument being default argument. I am not sure why two different results on different brackets like ( and {
2nd Sep 2024, 5:37 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
maybe https://stackoverflow.com/questions/33185543/delegating-constructors-in-c-or so yeah, use of {} is the recommended way. () can lead to ambiguities. And I guess I was wrong in my assumption about the compiler. Using {} does let it construct arrays properly.
2nd Sep 2024, 5:58 AM
Bob_Li
Bob_Li - avatar
+ 1
from: https://www.geeksforgeeks.org/when-do-we-use-initializer-list-in-c/ "Parameter vs Uniform Initialization in C++ It is better to use an initialization list with uniform initialization {} rather than parameter initialization () to avoid the issue of narrowing conversions and unexpected behavior. It provides stricter type-checking during initialization and prevents potential narrowing conversions"
2nd Sep 2024, 7:00 AM
Bob_Li
Bob_Li - avatar
+ 1
Thanks Bob_Li
2nd Sep 2024, 1:03 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Ketan Lalcheta {(1,2), (3,4)} will not automatically construct a UDT array. The compiler is not that smart. Unless you write your own custom array constructor. The result is a mystery to me, too. And there is that warning message... Also, fill out the methods before returning *this ... https://sololearn.com/compiler-playground/c48inhmbWXGS/?ref=app
2nd Sep 2024, 1:37 AM
Bob_Li
Bob_Li - avatar
0
I could not get your first few statements. I do know that assignment operators are not doing assignment, but that's not the issue ( because those are not called yet otherwise cout statement would print out something)
2nd Sep 2024, 3:43 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
in your first closure, UDT myarray = {(1,3), (4,5)}; is not the same as: UDT myarray[] = {UDT(1,3),UDT(4,5)}; as you may be assuming it will do. how it even works is a mystery to me. you can even use UDT myarray[] = {(3), (5)}; or UDT myarray[] = {(1,2,3),(4,5,6)}; to produce the same result, and I am at loss on how the compiler interprets this. It seems like your default b=10 argument makes the comipler treat the constructor as a single argument overload, too . And only using the last value to assign to m_a(a) is another mystery behavior. 😅 So I would conclude that constructing your array this way is undefined or ambiguous behavior...
2nd Sep 2024, 4:34 AM
Bob_Li
Bob_Li - avatar