Why copy constructor argument should be const in C++?
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. This is one good reason for passing reference as const, but there is more to it. For example, predict the output of following C++ program. Assume that copy elision is not done by compiler.
Compiler Error in line "Test t2 = fun();"
The program looks fine at first look, but it has compiler error. If we add const in copy constructor, the program works fine, i.e., we change copy constructor to following.
Or if we change the line “Test t2 = fun();” to following two lines, then also the program works fine.
In above codes, what’s actually happening?
It gets executed but copy constructor is not called, instead it calls the default constructor where assignment operator is overloaded. Even if we have an explicit overloaded assignment operator, it is not going to call it.
The function fun() returns by value. So the compiler creates a temporary object which is copied to t2 using copy constructor in the original program (The temporary object is passed as an argument to copy constructor). The reason for compiler error is, compiler created temporary objects cannot be bound to non-const references and the original program tries to do that. It doesn’t make sense to modify compiler created temporary objects as they can die any moment.
This article is compiled by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above