다음을 통해 공유


Initializing Objects Allocated with new

An optional initializer field is included in the grammar for the new operator. This allows new objects to be initialized with user-defined constructors. For more information about how initialization is done, see Initializers. The following example illustrates how to use an initialization expression with the new operator:

// expre_Initializing_Objects_Allocated_with_new.cpp
class Acct
{
public:
    // Define default constructor and a constructor that accepts
    //  an initial balance.
    Acct() { balance = 0.0; }
    Acct( double init_balance ) { balance = init_balance; }
private:
    double balance;
};

int main()
{
    Acct *CheckingAcct = new Acct;
    Acct *SavingsAcct = new Acct ( 34.98 );
    double *HowMuch = new double ( 43.0 );
    // ...
}

In this example, the object CheckingAcct is allocated using the new operator, but no default initialization is specified. Therefore, the default constructor for the class, Acct(), is called. Then the object SavingsAcct is allocated the same way, except that it is explicitly initialized to 34.98. Because 34.98 is of type double, the constructor that takes an argument of that type is called to handle the initialization. Finally, the nonclass type HowMuch is initialized to 43.0.

If an object is of a class type and that class has constructors (as in the preceding example), the object can be initialized by the new operator only if one of these conditions is met:

  • The arguments provided in the initializer agree with those of a constructor.

  • The class has a default constructor (a constructor that can be called with no arguments).

Access control and ambiguity control are performed on operator new and on the constructors according to the rules set forth in Ambiguity and Initialization Using Special Member Functions.

No explicit per-element initialization can be done when allocating arrays using the new operator; only the default constructor, if present, is called. See Default Arguments for more information.

If the memory allocation fails (operator new returns a value of 0), no initialization is performed. This protects against attempts to initialize data that does not exist.

As with function calls, the order in which initialized expressions are evaluated is not defined. Furthermore, you should not rely on these expressions being completely evaluated before the memory allocation is performed. If the memory allocation fails and the new operator returns zero, some expressions in the initializer may not be completely evaluated.

See Also

Concepts

new Operator (C++)