Explicit Assignment vs Implicit Assignment

Freesnöw picture Freesnöw · Jul 19, 2011 · Viewed 19.6k times · Source

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?

Answer

Fred Foo picture Fred Foo · Jul 19, 2011

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