+ 1

Why operator+(MyClass &obj) rather than operator+(MyClass obj)?

It seems that operator+(MyClass &obj) and operator+(MyClass obj) give the same output 67. Does this mean the two work in the same way?

8th Mar 2020, 11:27 PM
Zhanzhi Jiang
Zhanzhi Jiang - avatar
7 Respostas
+ 4
~ swim ~ const int* pint ... int* const pint ... const MyClass& obj ... MyClass const& obj ... Those are all the same?
9th Mar 2020, 7:38 AM
Ipang
+ 3
http://www.cplusplus.com/doc/tutorial/functions/ scroll down to:- "Efficiency considerations and const references." Although it uses "strings" in the example, the explanation is still relevant (and why/when to use a const reference).
8th Mar 2020, 11:46 PM
rodwynnejones
rodwynnejones - avatar
+ 3
That's something a lot of programmers do to avoid copying. If MyClass was a class with like 100 member variables, it would take a while to copy all those in a new MyClass object. So instead you create a reference to it which is instant. It is prefered to be constant so you make sure that you won't change it (if you don't want to) So it would be: operator+(const MyClass&obj)
9th Mar 2020, 9:45 PM
xaralampis_
xaralampis_ - avatar
+ 2
~ swim ~ It may be just the right time, and an added point to explain the difference between this; const <type>& something And this; <type> const& something Usage preferences and best practices of each would be a bonus for learners 👍
9th Mar 2020, 5:56 AM
Ipang
+ 2
~ swim ~ I recall you once told me they are different. So I thought maybe share for a wider scope. Alright then, no problem 👌
9th Mar 2020, 7:09 AM
Ipang
+ 2
~ swim ~ IIRC we were talking about the `const` position, and in regards to reference, not about pointers.
9th Mar 2020, 7:23 AM
Ipang
+ 2
~ swim ~ Okay I read that post ... Thank you 🙏
9th Mar 2020, 7:46 AM
Ipang