An optional new-initializer field is included in the syntax 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 in Chapter 7.
The following example illustrates how to use an initialization expression with the new operator:
#include <iostream.h>
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;
};
void 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:
Access control and ambiguity control are performed on operator new and on the constructors according to the rules set forth in Ambiguity in Chapter 9 and Initialization Using Special Member Functions in Chapter 11.
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 in Chapter 7 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.