0

What is the difference between:

long long int flag=n-1; and long long int flag(n-1);

Are these things same?I have seen the latter couple of time but have no proper idea about it.

chota bheem
  • 371
  • 3
  • 8
  • 20

3 Answers3

6

long long int flag = n-1 is copy initialization. For class types, this only considers non-explicit constructors and user-defined conversions.

long long int flag(n-1) is direct initialization. This considers all constructors and user-defined conversions.

However, these differences only matter for class types. For fundamental types, there is no difference.

Pradhan
  • 16,391
  • 3
  • 44
  • 59
4

Strictly speaking, the first one is called "copy initialization" and the second one is called "direct initialization". For primitive types, there is no difference in code behavior.

More details can be found at http://en.cppreference.com/w/cpp/language/initialization.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

For built-in types like the ones you listed, there is no difference.

But if you were dealing with objects, then the first would call the assignment operator, and the second would call the copy constructor.

So if you had overloaded the assignment operator and copy constructor, then

operator=(const Object& rhs)

would be called by the first, and

Object(const Object& rhs)

would be called by the second.

It's important to note this because of the differences in the way these functions behave. The copy constructor of a derived object will always call all the base objects' constructors. But creating an object will always automatically call its constructor anyway, and this will automatically call the base constructors also.

So, for instance, if you created an object and then assigned it

Object o;
o = n - 1;

Then you would be calling the object's constructor, all of its base constructors, and then its assignment operator. This is why it's generally best to use the copy constructor for objects. For built-in types it doesn't matter.

A. Duff
  • 4,097
  • 7
  • 38
  • 69