Freigeben über


Conversions

Objects of a given class type can be converted to objects of another type. This is done by constructing an object of the target class type from the source class type and copying the result to the target object. This process is called conversion by constructor. Objects can also be converted by user-supplied conversion functions.

When standard conversions (described in Standard Conversions) cannot completely convert from a given type to a class type, the compiler can select user-defined conversions to help complete the job. In addition to explicit type conversions, conversions take place when:

  • An initializer expression is not the same type as the object being initialized.

  • The type of argument used in a function call does not match the type of argument specified in the function declaration.

  • The type of the object being returned from a function does not match the return type specified in the function declaration.

  • Two expression operands must be of the same type.

  • An expression controlling an iteration or selection statement requires a different type from the one supplied.

A user-defined conversion is applied only if it is unambiguous; otherwise, an error message is generated. Ambiguity is checked at the point of usage. Hence, if the features that cause ambiguity are not used, a class can be designated with potential ambiguities and not generate any errors. Although there are many situations in which ambiguities arise, these are two leading causes of ambiguities:

  • A class type is derived using multiple inheritance, and it is unclear from which base class to select the conversion (see Ambiguity).

  • An explicit type-conversion operator and a constructor for the same conversion exist (see Conversion Functions).

Both conversion by constructor and conversion by conversion functions obey access control rules, as described in Member-Access Control. Access control is tested only after the conversion is found to be unambiguous.

For additional information, see Conversion Constructors.

See Also

Concepts

Special Member Functions