I am reading up on copy constructors and the way they typically receive the parameters as constant references. Why should the copy constructor accept its parameter by reference in C++? I wrote a code snippet to test that when a parameter is received by value, whether a copy is created( as stated in the accepted answer of the provided link). But I don't see the constructor called when an object is received by value. Please explain why? And isn't a copy created when an object is returned by value too? again no constructor called there as well. Why?
class Vector
{
public:
Vector(){cout << "Vector constructor"<<endl;}
~Vector(){cout << "Vector destructor"<<endl;}
};
Vector use(Vector z)
{
cout << "At call" << endl;
Vector v;
cout << "after definition" << endl;
return v;
}
int main()
{
Vector t;
cout << "After irrelevant" << endl;
use(t);
cout << "After use"<< endl;
}
The output looks as follows:
Vector constructor
After irrelevant
At call
Vector constructor
after definition
Vector destructor
Vector destructor
After use
Vector destructor
Update1: I had missed adding the copy constructor in the initial example. Once that is done the code behaves as expected.