#include <iostream>
using namespace std;
class Student
{
public :
Student() { };
Student(const Student& s) { cout << "COPY CONSTRUCTOR CALLED\n";}
};
Student f(Student u)
{
Student v(u);
Student w = v;
return w;
}
main()
{
Student x;
Student y = f(f(x));
}
According to me there should be 8 calls as each function call calls the copy constructor 4 times.
1) copying x to parameter u
2) copying u to v
3) copying v to w
4 ) returning w
Please help me. I am having lots of difficulty in understanding these concepts.
Each function call will call the copy constructor 3 times. This is due to Return Value Optimization (RVO). The first call will call the copy constructor 3 times and the second call will call the constructor 2 times only because the return value of the first is being passed on to the second.
The first call the copy constructor is called at:
The second time the copy constructor is called at:
At other places, optimization is done by the compiler.