views:

200

answers:

1

Just a quick syntax question. I'm writing a map class (for school).

If I define the following operator overload:

template<typename Key, typename Val> class Map {...
Val* operator[](Key k);

What happens when a user writes:

Map<int,int> myMap;
map[10] = 3;

Doing something like that will only overwrite a temporary copy of the [null] pointer at Key k. Is it even possible to do:

map[10] = 3;
printf("%i\n", map[10]);

with the same operator overload?

+4  A: 

The way it works with std::map is that, if the key doesn't exist, the map class will insert a default value and then return an lvalue (an assignable reference to the value associated with the key), so it can be assigned a new value.

So, in the following code sample, assuming map is empty, this will insert 10 into the map and associate it with a value of 3.

map[10] = 3;

With your custom map class, operator[] should first check if the Key k exists, and if not, insert a new key/value pair (using the default constructor of typename Val) into the map. You can then return a reference to the Value associated with the new key, so the user can assign a value to it. Note that this means that Val must be Assignable and have a default constructor.

This allows operator[] to be used both for insertion and lookup. You should also overload a const version of operator[], which of course only supports lookup.

Edit: I now noticed in your code that you are returning a pointer. If you want to use the insert/lookup paradigm for operator[] used by std::map, it makes more sense to return a reference. Returning a pointer gives you the advantage that you can examine the return value of operator[] for NULL to check if the key doesn't exist, but again, if you want operator[] to provide both lookup and insert functionality, a reference would be the way to go here.

Charles Salvia
so I should define my overload asVal and ofc ensure that I initialize appropriately, even if there isn't anything there.
Lanissum
That is correct.
Charles Salvia
Thanks a bunch; kind of a shame that I have to make objects, even when it's not 'needed'.
Lanissum
Well, you don't *have* to do it that way. The [] operator is provided strictly for the class user's convenience. The user can always use normal find/insert functions.
Charles Salvia
Also, it's preferable to define your overload as: `Val` so you can pass k by reference, rather by value.
Charles Salvia