1

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?

2, which operator will be chosen when I write Mytype[i] = 0 and double x = Mytype[i]?

Patrick
  • 181
  • 1
  • 1
  • 11
  • 2
    1) Yes. 2) Depends on whether `Mytype` instance is `const`. In both cases. – Algirdas Preidžius Sep 07 '18 at 07:36
  • If I declare `Mytpe` as `const`? – Patrick Sep 07 '18 at 07:37
  • 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 07 '18 at 07:39
  • 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 07 '18 at 07:47
  • 1
    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](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)? – Algirdas Preidžius Sep 07 '18 at 07:53
  • This code is from a blog which teach the curiously recurring template pattern, and it's not complete project. Thanks for the link. I'll build a minimum project to test it. ^-^ – Patrick Sep 07 '18 at 07:58

1 Answers1

0

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.

2) It depends solely on the constness of Mytype. However, double x = Mytype[i] will result in a copy in either case.

darune
  • 10,480
  • 2
  • 24
  • 62