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]






1) Yes. 2) Depends on whether Mytype instance is const. In both cases.

– Algirdas Preidžius
Sep 7 '18 at 7:36



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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)