Assignment vs. Initialization

Consider the following two code fragments:

int i;

i = 3;

and

int i = 3;

In C, these two fragments have the same effect, and can be regarded as the same. In C++, however, they are very different. In the first example, the integer i is assigned a value. In the second example, it is initialized with a value.

The differences are as follows:

An assignment occurs when the value of an existing object is changed; an object can be assigned new values many times.

An initialization occurs when an object is given an initial value when it is first declared; an object can be initialized only once.

One way to illustrate the difference is to consider variables declared as const. A constant variable can only be initialized; it cannot be assigned a new value. (Similarly, references are initialized with a variable, but they cannot be assigned a new variable.)

This distinction becomes important when using objects. Consider the previous examples with the integers replaced by String objects. Here's an assignment:

String myString( "this is my string" );

String yourString;

yourString = myString; // Assign one String the value of another

Here's an initialization:

String myString( "this is my string" );

String yourString = myString; // Initialize one String with another

As previously described, the assignment statement causes the compiler to invoke the operator= function defined for the class. However, the initialization does not invoke the same function. The operator= function can only be called for an object that has already been constructed. In the above example, yourString is being constructed at the same time that it receives the value of another object. To construct an object in this way, the compiler invokes a special constructor called the “copy constructor.”