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?
When we create our own copy constructor, we pass an object by reference and we generally pass it as a const reference. One reason for passing const reference is, we should use const in C++ wherever possible so that objects are not accidentally modified.
According to C++ copy constructor, we pass an object by reference to the copy function Object() { [native code] }, and we usually pass it as a const reference. One justification for passing a const reference is that it can use const wherever possible in C++ to avoid unintentionally changing objects.
Constructors may be declared as inline , explicit , friend , or constexpr . A constructor can initialize an object that has been declared as const , volatile or const volatile . The object becomes const after the constructor completes.
Not just a copy; it is also a const copy. So you cannot modify it, invoke any non-const members from it, or pass it as a non-const parameter to any function. If you want a modifiable copy, lose the const decl on protos .
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-constructors
option with GCC, then the copy-elision will not be performed, and the copy-constructor will be called. The GCC doc says,
-fno-elide-constructors
The C++ standard allows an implementation to omit creating a temporary which is only used to initialize another object of the same type. Specifying this option disables that optimization, and forces G++ to call the copy constructor in all cases.
The compiler decided to optimize out the copy construction as it's allowed to do, even when it accepted the argument by const reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With