0

Okay we have created a reference to Date So, that any change made in Date via this function

So, that the changes may reflect in main

but why do we make change if we hade declared it const ?

What's benifit of using const

ostream& operator<<(ostream& os, const Date& d){
return os << '(' << d.year()
<< ',' << d.month()
<< ',' << d.day() << ')';
}
source : Programming : Principles and structure ``` 




  • Using a reference as a parameter is not only meant to be used to change its value, it also prevents compiler from generating a copy of the object, which may be expensive in some cases. – Hawky Jan 12 '20 at 14:11
  • You use `const` when you *don't* want to make changes, merely inspect. And a `const &` is *usually* cheaper than copying the object. – Jesper Juhl Jan 12 '20 at 14:11
  • Benefit of const that this object cannot be changed inside the function. Therefore, is somebody calls that function, she can be sure that the object won't be changed – rhaport Jan 12 '20 at 14:11
  • Passing by reference avoids copying an object - which can be beneficial if the object is expensive to copy for some reason. Passing by `const` reference allows the benefit of passing by reference with an assurance that the passed object will not be unintentionally changed. – Peter Jan 12 '20 at 14:12
  • 1
    I dunno why, but I suspect the trigger to this question is "why did making the reference `const` break this code?", and the likely answer is "because `year()`, `month()`, and `day()` were/are not marked `const`. – WhozCraig Jan 12 '20 at 14:14
  • @WhozCraig - What you say may, or may not, be true. If it is true, then the OP should have asked that specific question, rather than the one they asked. There was certainly no indication in this question that the code sample worked if the `Date` argument was passed by value, but broke if the `Date` was passed by `const` reference. – Peter Jan 12 '20 at 14:58
  • this code is picked from book by stroustup itself and i had that question arised ,,,,, It must work perfectly – Rohit Garg Jan 12 '20 at 15:38

0 Answers0