For the following code :
#include<iostream>
using namespace std;
class Test
{
public:
Test(const Test &t) { cout<<"Copy constructor called"<<endl;}
Test() { cout<<"Constructor called"<<endl;}
};
Test fun()
{
cout << "fun() Called
";
Test t;
return t;
}
int main()
{
Test t1;
Test t2 = fun();
return 0;
}
I am really confused regarding when the copy constructor is called ? Like if I am running the above program copy constructor is not called. That means if I am messing up with the parameters passed to the copy constructor (eliminating const keyword) it shouldn't show any compiler error. But its showing
"no matching function for call to 'Test::Test(Test)' "
Moreover, the fun() is returning an object of type test , which is created during fun() execution. Why the copy constructor is not called here ?
int main()
{
fun();
return 0;
}
also if I am making following changes to main function why copy constructor is called only once , not twice ?
int main()
{
Test t2 = fun();
Test t3 = t2;
return 0;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…