I'm reading a tutorial for C++ but it didn't actually give me a difference (besides syntax) between the two. Here is a quote from the tutorial.
You can also assign values to your variables upon declaration. When we assign values to a variable using the assignment operator (equals sign), it’s called an explicit assignment:
int nValue = 5; // explicit assignment
You can also assign values to variables using an implicit assignment:
int nValue(5); // implicit assignment
Even though implicit assignments look a lot like function calls, the compiler keeps track of which names are variables and which are functions so that they can be resolved properly.
Is there a difference? Is one more preferred over the other?
The first is preferred with primitive types like int
; the second with types that have a constructor, because it makes the constructor call explicit.
E.g., if you've defined a class Foo
that can be constructed from a single int
, then
Foo x(5);
is preferred over
Foo x = 5;
(You need the former syntax anyway when more than one argument is passed, unless you use Foo x = Foo(5, "hello");
which is plain ugly and looks like operator=
is being called.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With