Explicit Initialization

C++ supports two forms of explicit initialization.

The equal-sign initialization syntax is different from the function-style syntax, even though the generated code is identical in most cases. The difference is that when the equal-sign syntax is used, the compiler has to behave as if the following sequence of events were taking place:

The constructor must be accessible before the compiler can perform these steps. Even though the compiler can eliminate the temporary creation and copy steps in most cases, an inaccessible copy constructor causes equal-sign initialization to fail. Consider the following example:

class anInt
{
    anInt( const anInt& );    //  Private copy constructor.
public:
    anInt( int );             //  Public int constructor.
};
...
anInt myInt = 7;              //  Access-control violation. Attempt to
                              //   reference private copy constructor.
anInt myInt( 7 );             //  Correct; no copy constructor called.

When a function is called, class-type arguments passed by value and objects returned by value are conceptually initialized using the form:

type-name name = value

For example:

String s = "C++";

Therefore, it follows that the argument type must be a type that can be converted to the class type being passed as an argument. The class’s copy constructor, as well as user-defined conversion operators or constructors that accept the type of the actual argument, must be public.

In expressions that use the new operator, the objects allocated on the free store are conceptually initialized using the form:

type-name name( initializer1, initializer2, ... initializern )

For example:

String *ps = new String( "C++" );

Initializers for base-class components and member objects of a class are also conceptually initialized this way. (For more information, see Initializing Bases and Members.)