Question

Take this for example:

const Integer operator+(const Integer& left, const Integer& right) {
  return Integer(left.i + right.i); 
}

(taken from page 496 of Thinking in C++)

What is the part after the return statement? A cast (to make the result of the sum an Integer) or a call to the constructor of the class Integer? Or maybe something else that I ignore..

This is the constructor:

Integer(long ll = 0) : i(ll) {}

Edit:

i it's long int.

Was it helpful?

Solution

Casting means "changing an entity of one data type into another". That said, you can consider Integer() as a cast from long to Integer, as the two types are related and the operation translates into "build an object of type B, starting with an object of type A".

With this syntax, there is no protection against misuse, i.e. if the constructor takes only one parameter, the parameter might not be used to build an object directly representing the first (e.g. each QWidget takes a pointer to the parent, but it is not representing its parent, obviously), and you cannot do anything to prevent this. You could block implicit initialization by marking single-parameter constructor as explicit, but nothing more.

The syntax for old-style casts and constructors with only one parameter is exactly the same, and that's the reason why a new syntax was created for the first: use new style (explicit) C++ syntax for casts, that is, const_cast, dynamic_cast, static_cast or reinterpret_cast as appropriate.

In the very words of Bjarne Stroustrup, this verbose casting syntax was introduced to make clear when a cast is taking place. Note that having four forms also allows for proper differentiation of the programmer's intent.

Finally, int() and such are considered old-style for plain types (int, long, etc.) and newvar = (T)oldvar form exists only because of C compatibility constraint.

OTHER TIPS

Its a constructor call.

Object creation in c++ will be in 2 ways,

Integer* i = new Integer(args); //A Pointer i , pointing to the object created at a memory location.

or

Integer i = Integer(args); //Object i

Your case is 2nd one, but the initialized object is not assigned to i. Rather it is passed as it is.

Moreover, A cast could be trivial if it is (DataType) value., In this case it would be surely a cast.

But in the case of DataType(value) if it is a primitive type, it would be a cast, but if it is a non-primitive type surely it will be a constructor call.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top