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.
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
- Copy Constructor in C++
- When should we write our own copy constructor?
- When is copy constructor called?
- Copy constructor vs assignment operator in C++
- Advanced C++ | Virtual Copy Constructor
- Difference between const int*, const int * const, and int const *
- Difference between const char *p, char * const p and const char * const p
- Different methods to copy in C++ STL | std::copy(), copy_n(), copy_if(), copy_backwards()
- Argument Coercion in C/C++
- Variable Length Argument in C
- C function argument and return values
- Const Qualifier in C
- C++ | const keyword | Question 5
- How to modify a const variable in C?
- Diffference between #define and const in C?