Steven
Steven

Reputation: 19

C++ overload map [ ] operator

I have 2 overloaded operator declaration that I need help understanding.

template<class KEY, class T>
const T& Map<KEY, T>::operator [](const KEY& key) const { }

and

template<class KEY, class T>
T& Map<KEY, T>::operator [](const KEY& key) { }

the first [] is used to access the value/return value, i.e std::cout<<m["x"]<<std::endl;

the second [] is for assignment, i.e m["x"] = 1;

The question I have pertains to the 2nd []. If I were to do m["z"] = 10, how does 10 get stored as the value associated with key z? Looking at the function declaration, I only see the key, not value.

I tried doing m_value = T();, but I'm not sure what T() is.

Thank you

Upvotes: 1

Views: 4069

Answers (2)

Malekai
Malekai

Reputation: 45

The difference is the const. In theory you could use the 2nd for output too (and may be doing as they are both basically the same function with the same parameters. But that's not your question :)

All your 2nd "[]" is doing is giving you access to the item stored at "z", the assignment is done using the "=" operator which you have not shown to be overloaded here.

Therefore the 10 gets stored using the standard version of the "=" operator using your 2nd "[]" operator as the access method.

Hope this helps

Upvotes: 0

Mike Seymour
Mike Seymour

Reputation: 254481

The function returns a reference:

template<class KEY, class T>
T& Map<KEY, T>::operator [](const KEY& key) { }
 ^ that means "reference"

That will be a reference to an object stored in the map. Assigning to the reference will assign to that object.

Upvotes: 2

Related Questions