Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Copy constructor with non-const argument

20 views
Skip to first unread message

Joseph Hesse

unread,
Feb 16, 2023, 10:34:36 AM2/16/23
to
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? In the following example the code in the body
executes first. Is this always the case?

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
}

Markus Schaaf

unread,
Feb 16, 2023, 11:11:57 AM2/16/23
to
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

Andrey Tarasevich

unread,
Feb 17, 2023, 1:28:50 AM2/17/23
to
On 02/16/23 7:34 AM, Joseph Hesse wrote:
> 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?

Member and base initialization is always carried out first.

> In the following example the code in the body
> executes first.

Where did you get this strange idea?

> #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
> }

Aaand? '7' is the expected output. What made you conclude that "body
executes first" here?

--
Best regards,
Andrey
0 new messages