Initialisation and assignment

Oh my. Initialization and assignment. Well, that’s confusion for sure!

To initialize is to make ready for use. And when we’re talking about a variable, that means giving the variable a first, useful value. And one way to do that is by using an assignment.

So it’s pretty subtle: assignment is one way to do initialization.

Assignment works well for initializing e.g. an int, but it doesn’t work well for initializing e.g. a std::string. Why? Because the std::string object contains at least one pointer to dynamically allocated memory, and

  • if the object has not yet been initialized, that pointer needs to be set to point at a properly allocated buffer (block of memory to hold the string contents), but

  • if the object has already been initialized, then an assignment may have to deallocate the old buffer and allocate a new one.

So the std::string object’s assignment operator evidently has to behave in two different ways, depending on whether the object has already been initialized or not!

Of course it doesn’t behave in two different ways. Instead, for a std::string object the initialization is taken care of by a constructor. You can say that a constructor’s job is to take the area of memory that will represent the object, and change the arbitrary bits there to something suitable for the object type, something that represents a valid object state.

That initialization from raw memory should ideally be done once for each object, before any other operations on the object.

And the C++ rules effectively guarantee that. At least as long as you don’t use very low level facilities. One might call that the C++ construction guarantee.

So, this means that when you do

    std::string s( "one" );

then you’re doing simple construction from raw memory, but when you do

    std::string s;
    s = "two";

then you’re first constructing s (with an object state representing an empty string), and then assigning to this already initialized s.

And that, finally, allows me to answer your question. From the point of view of language independent programming the first useful value is presumably the one that’s assigned, and so in this view one thinks of the assignment as initialization. Yet, at the C++ technical level initialization has already been done, by a call of std::string‘s default constructor, so at this level one thinks of the declaration as initialization, and the assignment as just a later change of value.

So, especially the term “initialization” depends on the context!

Simply apply some common sense to sort out what Someone Else probably means.

Cheers & hth.,

Leave a Comment