Type Conversions


Syntax

 type_conversion_expression:
        postfix_expression
        type_name(expression_list) {expression_list} 
 
 expression_list:
        expression
        expression expression_list
        expression, expression_list

Notes

When type_name is followed by a pair of parentheses containing no expression list, an object of the specified type is constructed. If type_name is of class type the class must possesses a default constructor, and that default constructor is called. When a list with braces occurs in the expression it contains an expression list of initializers. In this case, the type should possess an operator<< which is called for each initializer.

When type_name is followed by an expression list enclosed in parentheses, an object of that type is created. If the list contains one or more items, the specified type must be a class with a suitably declared constructor. When a list with braces occurs in the expression it contains an expression list of initializers. In this case, the type should possess an operator<< which is called for each initializer.

See also the topic of type casting.

Type conversions are the primary means by which classes are instantiated. This precludes using the new operator all the time. For example, consider the following program.

using system

space conversions
{
    claass conversions
    {
       conversions()
       {
           i = new integer(100)    // Create an integer via the new operator.
           j = integer(100)        // Create an integer via type conversion.
           cout << i << "\n"
           cout << j << "\n"
       }
    }
}

100 is printed out twice. The new operator is a primary expression. The variable i is created by such an expression. The variable j is instantiated via type conversion. Type conversion calls the new operator for the type. So this is a shorthand for creating a new type. Almost all new types are instantiated through type conversion operators.