Using const before the returned type. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 1

Using const before the returned type.

Why are using a classifier const before the returned type Date in the next code snippet: ... const Date &Date::operator+=(int additionalDays) { for (int i = 0; i < additionalDays; i++) helpIncrement(); return *this; } ..?

11th Nov 2017, 8:42 AM
ms_Shifu
ms_Shifu - avatar
7 Answers
+ 2
const "freezes" the value of the variable, prwventing it from further change and ensuring that it remains the same
11th Nov 2017, 9:17 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 1
generally spoken, you use const always to protect the variable (so it will not be changed). in this case you return a reference, so it would lead to unexpected behaviour if you do not make it const! (why,? wrong question! what does reference mean ;))
11th Nov 2017, 12:24 AM
Gunther Strauss
Gunther Strauss - avatar
0
Thanks, but it's wrong answer ;), because in other places of the code const before Date don't used: Date &Date::operator++() { helpIncrement(); return *this; }
11th Nov 2017, 8:43 AM
ms_Shifu
ms_Shifu - avatar
11th Nov 2017, 8:53 AM
Gunther Strauss
Gunther Strauss - avatar
0
Output https://code.sololearn.com/cZ6VOslmWLg1/?ref=app: 2 member: 2 3 member: 3 ... are you sure?
11th Nov 2017, 9:27 AM
ms_Shifu
ms_Shifu - avatar
0
The use of the constant did not affect
11th Nov 2017, 9:29 AM
ms_Shifu
ms_Shifu - avatar
- 1
I updated the examle, hope it is now more clear. at this point I would explain it more extensively, but you don't trust me anyway or don't want to look up what reference means... [edit] if you get confused with the test variables, just play with the code and see what happens ;) [edit2] what just came to my mind, do you struggle to understand the operators itself? I don't know your level of experience...
11th Nov 2017, 9:36 AM
Gunther Strauss
Gunther Strauss - avatar