I'm new to C++ and trying to understand something. I have this code in my main.cpp:
Radio r = Radio("PSR", 100.8);
or that code:
Radio r("PSR", 100.8);
Both seem to work and doing the same thing. So what's the difference?
Radio r = Radio("PSR", 100.8);
is copy initialization while Radio r("PSR", 100.8);
is direct initialization.
From C++17 due to mandatory copy elison both are the equivalent.
Radio r = Radio("PSR", 100.8); //from C++17 this is same as writing Radio r("PSR", 100.8);
But prior to C++17, the first case Radio r = Radio("PSR", 100.8);
may result in the creation of a temporary using which r
is copy initialized. This is because prior to C++17, there was non-mandatory copy elison.
Another thing to note is that if you were to write:
type name(); //this is a function declaration
the above is a declaration for a function named name
which has the return type of type
and has 0
parameters.