class x
{
int a;
public:
x()
{
cout<<"\n\ndefault constructor";
}
x(x& obj)
{
cout<<"\n\ncopy constructor";
}
x fun()
{
x ob;
return ob;
}
};
int main()
{
x ob1;
x ob2=ob1.fun();
return 0;
}
initially, this code gave an error ” no matching function for call to ‘x::x(x)’”,
when i changed the copy constructor to
x(const x& obj)
{
cout<<"\n\ncopy constructor";
}
the output becomes
default constructor
default constructor
still the copy constructor is not executing…. why?
That is called copy-elision done by the compiler, and that is allowed by the language specification.
See this wiki entry:
As for why non-const version is giving compilation error because
obj1.fun()return a temporary object which cannot be bound to non-const reference, but it can bind to const reference, so the const version compiles fine. Once you make it const reference, it is used only for semantic check, but the compiler optimizes the code, eliding the call to the copy-constructor.However, if you compile it with
-fno-elide-constructorsoption with GCC, then the copy-elision will not be performed, and the copy-constructor will be called. The GCC doc says,