Why is the output foo3
equal to 3
?
i would suggest, when bar(foo1)
is called, the function bar
creates a copy of foo1
on the stack, so it's value is equal to 0, when this value is returned, the copy-constructor for foo3
increments the value again so it should be 2?
Thanks in advance.
this is my code:
#include <iostream>
struct Foo {
Foo()
: x(0)
{
}
Foo(const Foo& foo)
: x(foo.x + 1)
{
}
int x;
};
Foo bar(Foo foo)
{
foo.x++;
return foo;
}
int main()
{
Foo foo1;
Foo foo2 = foo1;
std::cout << "A:" << foo1.x << std::endl;
std::cout << "B:" << foo2.x << std::endl;
Foo foo3 = bar(foo1);
std::cout << "C:" << foo3.x << std::endl;
}
output:
A:0
B:1
C:3