The assignment operator and initialization

You asked

when i initialize a variable am I doing it with the assignment operator ?

and said

when we initialize a variable we are giving it a new value with the assignment operator

But, no, you are not. The symbol = is used for both copy-initialization and assignment, but initialization does NOT use the assignment operator. Initialization of a variable actually uses a constructor.

In copy-initialization, it uses a copy constructor.

type x = e; // NOT an assignment operator

First e is converted to type, creating a temporary variable, and then type::type(const type&) initializes x by copying that temporary. type::operator=(const type&) is not called at all.

There is also direct initialization, which does not use the = symbol:

type x(e);
type x{e}; // since C++11
otherclass::otherclass() : x(e) {} // initialization of member variable

While both initialization and assignment give a variable a value, the two do not use the same code to do it.


Further details: With C++11 and later, if there is a move constructor, copy initialization will use it instead, because the result of the conversion is a temporary. Also, in copy-initialization, the compiler is permitted to skip actually calling the copy or move constructor, it can convert the initializer directly into the variable. But it still must check that the copy or move constructor exists and is accessible. And copy constructors can also take a non-const reference. So it might be type::type(type&&) that is used, or type::type(const type&&) (very uncommon), or type::type(type&) that is used, instead of type::type(const type&). What I described above is the most common case.

Leave a Comment