0

I would like to get and set the value of Test Class object using [] operator. But getting the following error:

lvalue required as left operand of assignment

Thanks in Advance.

class Candidate {
    public:
    Candidate(string name):
        name(name) {}
    string name;
};

template<typename _key, typename _value>
class Test {
    _key key;
    _value value;
    public:
    _value operator[](_key key) {
        return this->value;
    }
};

int main() {
    Test<string, Candidate*> test;
    test["something"] = new Candidate("name");
    Candidate* candidate = test["something"];

    return 0;
}
Eugene Sh.
  • 17,802
  • 8
  • 40
  • 61
  • Related: [this answer](https://stackoverflow.com/a/4421719/11941443) under the heading "Array Subscripting". – walnut Oct 24 '19 at 19:29
  • Please don't mark a question duplicate unless you're going to mark it duplicate of an actual question it is a duplicate of. A General Reference question is not a duplicate of this. – Xirema Oct 24 '19 at 19:31
  • https://stackoverflow.com/questions/37043078/c-overloading-array-operator – R Sahu Oct 24 '19 at 19:32

1 Answers1

2

For this kind of use, you need to return by reference, not by value.

_value& operator[](_key key) {
    return this->value;
}

You might also consider adding an overload for when the object is const.

_value const& operator[](_key key) const {
    return this->value;
}

Returning by value returns an expiring value, which cannot be assigned to per the assignment rules in C++, unless the value expressly permits this kind of assignment (and that usually represents a design flaw). You have to return an l-value, or a persistent reference, to actually assign to it.

Xirema
  • 19,889
  • 4
  • 32
  • 68
  • Just an FYI. https://stackoverflow.com/questions/37043078/c-overloading-array-operator is an exact duplicate. – R Sahu Oct 24 '19 at 19:38
  • @RSahu Alright, I've tagged it. The previous question that got tagged as a duplicate was wholly inappropriate, due to being far greater in scope than the simple syntactical error the user made. – Xirema Oct 24 '19 at 19:43