C++ Quiz26 of 173
Difficulty:
⬅️ Prev: 31Quiz ID: 32Next: 33 ➡️

According to the C++23 standard, what is the output of this program?

#include <iostream>

struct X {
  X() { std::cout << "a"; }
  X(const X &x) { std::cout << "b"; }
  const X &operator=(const X &x) {
    std::cout << "c";
    return *this;
  }
};

int main() {
  X x;
  X y(x);
  X z = y;
  z = x;
}
Hint

What is the difference between direct-initialization and copy-initialization? Do they in any way relate to the copy constructor and copy assignment operator?

Reveal answer

abbc

Explanation

The first line in main(), X x; is straightforward, it calls the default constructor.

The next two lines is the heart of the question: The difference between X y(x) and X z = y is not that the first calls the copy constructor, and the second calls the copy assignment operator. The difference is that the first is direct-initialization (§[dcl.init.general]¶15 in the standard) and the second is copy-initialization (§[dcl.init.general]¶14).

§[dcl.init.general]¶16.6.2:

Otherwise, if the initialization is direct-initialization, or if it is copy-initialization where the cv-unqualified version of the source type is the same class as (...) the class of the destination, constructors are considered.

So both our cases use the copy constructor.

Not until z = x; do we have an actual assignment that uses the assignment operator.

See https://stackoverflow.com/a/1051468 for a more detailed discussion of direct- vs copy-initialization.

⬅️ Prev: 31Quiz ID: 32Next: 33 ➡️