Sunday, July 12, 2009

C++, why is a copy constructor not needed when passing by reference?

Consider a class object passed to a function by reference. A copy constructor is not required for this. Why not?

C++, why is a copy constructor not needed when passing by reference?
Because with the reference, you have direct access to the object.





However, if you pass by value, the function will make a copy, which why you would then need a copy constructor.
Reply:Because you are using a direct reference to the object. Anything that you do to the object stays when you exit the function.





You only need to use a copy constructor when you pass by value and you don't want the object to be altered by your function.





You need to do some serious work to understand what all these homework questions you are asking mean otherwise you will never be a good programmer. Yahoo Answers is not a substitute for study.
Reply:When you pass by reference the object already exists, some where else it was constructed. A copy constructor actually makes another object of the same class.


No comments:

Post a Comment