Operator overload with a reference return in C++ class
Operator overload with a reference return in C++ class
What's the difference between this two function?
double &operator(size_t i) return features_[i];
double operator(size_t i) const return features_[i];
1, the first one allows to modify the features_[i]
but the second not?
features_[i]
2, which operator will be chosen when I write Mytype[i] = 0
and double x = Mytype[i]
?
Mytype[i] = 0
double x = Mytype[i]
Mytype
const
If I declare
Mytpe
as const
?– Patrick
Sep 7 '18 at 7:37
Mytpe
const
My comment should've hinted at the answer, but since the 2nd overload is marked as
const
, it will be chosen for const
instances, while the non-const
method (1st overload) will be chosen for non-const
instances.– Algirdas Preidžius
Sep 7 '18 at 7:39
const
const
const
const
If I only offer the first function, is there some risks for the
const Mytype
which tries to modify the return value? or the const
before Mytype
will guarantee that Mytype
will not assign the features_
?– Patrick
Sep 7 '18 at 7:47
const Mytype
const
Mytype
Mytype
features_
If you offer only the first overload, then it wouldn't get called if you tried to call it on the
const
object, since the compiler will only look for const
methods. That's the whole purpose of them - to be called on const
objects. Why didn't you just: 1) try-out such questions, yourself, and observe what errors the compiler gives you? 2) consider learning from a good C++ book?– Algirdas Preidžius
Sep 7 '18 at 7:53
const
const
const
1 Answer
1
1) Yes. Please note that the second one (const) returns a copy (return by value), which may be ok to modify, but will not modify the original in Mytype
.
Mytype
2) It depends solely on the constness of Mytype
. However, double x = Mytype[i]
will result in a copy in either case.
Mytype
double x = Mytype[i]
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
1) Yes. 2) Depends on whether
Mytype
instance isconst
. In both cases.– Algirdas Preidžius
Sep 7 '18 at 7:36