Joe Caraccio Joe Caraccio - 1 year ago 128
C++ Question

Overloading subscript operator

I have an example Map class in which I am trying to override the subscript operator. To allow users of the class to read and write to the Map.
Map["a"] being read, and Map["a"]="something" being the write of the class. However, I can't figure out how to use the assignment operator side of things, and allow a passed in value to replace it. Right now, if I try to assign a new value it just reads "segmentation fault"

Here is what I have so far:

VALUE_TYPE& Map::operator[](KEY_TYPE a){
cout << "hmm" << endl;


Map& Map::operator=(const Map &rhs){
//cout << "operator = " << endl;

Right now I don't have any of the code.. just wanted to see that they would get succesfully called.

What I can't seem to figure out is if I do something such as

Map["a"] = "hey";

I will get a segmentation fault. I was assuming that the assignment operator= would be called when I wanted to assign a specific key a new value. Am I doing something wrong?

By the way, VALUE_TYPE and KEY_TYPE are just defined as strings, each key has a value associated with it.

Answer Source

You're not assigning to the map but to the object returned by operator[].
(In m["a"] = "hey";, m["a"] is not a Map, it's a VALUE_TYPE&.)

The operator needs to return a reference to a valid object, otherwise the behaviour is undefined.

Smallest example I can come up with:

struct Mapp
    int& operator[](int i) { return member; }
    int member;

int main()
    Mapp m;
    m[0] = 12; // Assigns 12 to m.member

You also want to overload the const version of the operator.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download