Click here to Skip to main content
15,311,151 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I have a query regarding Copy construtor. And my question is:

As we all know the prototype of copy constructor is

MyClass (const MyClass &);

my question is, WHy do we need to pass CONST. As per my knowledge, Because no body by mistake should change the object, i am trying to copy from. Is there any other reason for making it CONST.

I was asked that we can give our own implementation for copy constructor. So in my overloaded copy construtor. I will make sure that my passed object is not getting changed. Then why do we need CONST.


Thanks in advance
Posted
Comments
Maarten Kools 29-Nov-13 4:48am
   
What does the const keyword have to do with the fact whether you want to overload the copy constructor? You can still do that. As for the reason, read this[^] (or do a search on the web for other articles regarding the subject).
Maciej Los 29-Nov-13 4:53am
   
It looks like an answer ;) My virtual 5!
Andreas Gieriet 29-Nov-13 5:02am
   
When you "make sure you do not change" the passed object, why do you want to get rid of the const in the signature?
The signature is the "guarantee" that you do not change the memory of the passed object inside the function. If as a client of your code I see no const in the signature, I must assume you change the object.
Cheers
Andi

That's a constraint. The compiler guarantees your implementation won't touch the passed object. Don't get me wrong, we know you are a good fellow, anyway we trust more the compiler.
   
Comments
Maciej Los 29-Nov-13 5:14am
   
The last sentence is my favorite ;)
+5!
CPallini 29-Nov-13 5:18am
   
Thank you. :-)
Your knowledge is correct: using const for *any* function parameter prevents* (accidentally) changing them inside the implementation of the function. It is a promise to the person calling that function, that the object being passed as parameter will not be changed.

Additionally it enables you to pass an expression to the function, rather than a variable: in that case, the compiler will create a temporary object that holds the result of the expression. If the parameter is not declared as const, then the compiler will raise an error, because passing a reference to a temporary that is not const is an error!

*: Of course, the implementation can still cast away const - it shouldn't, but it's possible.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900