I'm reading Prata's C++ book, and when talking about copy constructors, it says that this constructor is invoked when:
- Initializing a class object to the a class object of the same type.
- Passing an object by value to a function.
- Returning an object by value from a function.
Let say that we are working with a Vector
class.
For understanding sakes, throughout the examples in the current chapter we included in the constructors/destructor definitions string outputs, to indicate which and when each of them is called.
For instance, if we have
int main()
{
Vector v1; // print "Default constructor called"
Vector v2(9, 5); // print "Constructor called"
Vector v3 = v1; // print "Copy Constructor called"
return 0;
}
And Destructor called
would be printed in this case 3 times, when exiting main()
.
In order to check the 3 points above I've been playing with a dumb_display()
function, changing the type of the formal parameter/return value. In doing so, I got confused about what is indeed happening under the hood.
Vector dumb_display(Vector v)
{
Vector test(45, 67);
cout << "In dumb_display() function" << endl;
cout << v << endl;
return v;
}
Here:
Every time we return by value the passed argument as in the above function (argument either passed by value or reference) the copy constructor gets called.
- It makes sense. It satisfies point 3.
Every time we return an object defined in the function's body (e.g., changing return v;
by return test;
), the copy constructor isn't called.
- Point 3 isn't satisfied.
I'm having a hard time trying to understand this behaviour.
I don't know whether this is correct, but I think (since an automatic storage duration object is created once for the duration of the function call) once test
is created it, hasn't have to be created again, because the object "is already there". This brings the question:
Why does returning the passed argument call the copy constructor twice? Why does the same object have to be created twice for the duration of the call to the function?