I understand that when we define a class copy constructor of the class is necessary as Rule of three states. I also notice that the argument of the copy constructor is usually const
as the following codes illustrate:
class ABC {
public:
int a;
int b;
ABC(const ABC &other)
{
a = other.a;
b = other.b;
}
}
My question is what would happen if the argument of the copy constructor is not const:
class ABC
{
public:
int a;
int b;
ABC(ABC &other)
{
a = other.a;
b = other.b;
}
}
I understand that in some cases if the argument of the copy constructor is const then the second implementation would fail. Also if the argument of the copy constructor is const then the object to be copied will not change its content during the process. However, I do notice that some people still use the second implementation rather than the first one. Are there any reasons that the second implementation is preferred?
A
be modified inABC B(A)
? It makes little sense and would be quite non-intuitive behaviour. – Rurikauto_ptr
. Of course, given that even the standards committee couldn't get that right, it is a very bad idea to do so. – Chutneyconst
themselves. Probably and hopefully in a way which does not change &other. – Negressconst
. – Chutneyconst
and that was not, I would no longer need to work ;) And unfortunately, you may not be in a position to change the code... – Hydroxideconst_cast
in order to keep the decease quarantined. So it's still no excuse to make the constructor argument non-const. – Chutney