Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit Assignment vs Implicit Assignment

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?

like image 309
Freesnöw Avatar asked Jul 19 '11 18:07

Freesnöw


1 Answers

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.)

like image 106
Fred Foo Avatar answered Sep 28 '22 20:09

Fred Foo