Am 16.02.23 um 16:34 schrieb Joseph Hesse:
> If a non-const argument is given for a copy constructor, with a
> non-empty body, does the code in the body execute first or is the
> initialization first?
First initialization, then body.
> In the following example the code in the body
> executes first.
No.
>
> Thank you,
> Joe
>
> #include <iostream>
>
> class X {
> public:
> X(int u = 0) : x(u) {}
> X(X &rhs) : x(rhs.x) { x += 2; } // non-const argument for copy
> constructor
> int getx() const { return x; }
> private:
> int x;
> };
>
> int main() {
> X x1(5);
> X x2(x1);
> std::cout << x2.getx() << '\n'; // g++ and clang++ output 7
> }
Of course. `X x1(5)` calls `X::X(int)`, which initializes `x1.x`
to 5. Then `X x2(x1);` calls `X::X(X&)`, which initializes `x2.x`
to 5, and then adds 2.
BR