class MyContainerClass { public: int& operator[](unsigned int index); int operator[](unsigned int index) const;
Returning the link allows the user to use the result as an lvalue, as in your example MyInstance[3] = 5; . Adding a const overload ensures that they cannot do this if MyInstance is a variable or const reference.
But sometimes you want everything to look like this, but there really isnβt an int you can reference. Or maybe you want to allow several types on the right side of MyInstance[3] = expr; . In this case, you can use a dummy object that overloads the destination:
class MyContainerClass { private: class Index { public: Index& operator=(int val); Index& operator=(const string& val); private: Index(MyContainerClass& cont, unsigned int ind); MyContainerClass& m_cont; unsigned int m_ind; friend class MyContainerClass; }; public: Index operator[](unsigned int ind) { return Index(*this, ind); } int operator[](unsigned int ind) const;
source share