Reputation: 25551
Let's say I have a container class called MyContainerClass
that holds integers.
The []
operator, as you know, can be overloaded so the user can more intuitively access values as if the container were a regular array. For example:
MyContainerClass MyInstance;
// ...
int ValueAtIndex = MyInstance[3]; // Gets the value at the index of 3.
The obvious return type for operator[]
would be int
, but then the user wouldn't be able to do something like this:
MyContainerClass MyInstance;
MyInstance[3] = 5;
So, what should the return type for operator[]
be?
Upvotes: 4
Views: 408
Reputation: 72271
class MyContainerClass {
public:
int& operator[](unsigned int index);
int operator[](unsigned int index) const;
// ...
};
Returning a reference lets the user use the result as an lvalue, as in your example MyInstance[3] = 5;
. Adding a const
overload makes sure they can't do that if MyInstance
is a const
variable or reference.
But sometimes you want things to look like that but don't really have an int
you can take a reference to. Or maybe you want to allow multiple types on the right-hand side of MyInstance[3] = expr;
. In this case, you can use a dummy object which overloads assignment:
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;
// ...
};
Upvotes: 2
Reputation: 14672
int&
returning a reference allows you too use the returned value as a left-hand side of the assignment.
same reason why operator<<()
returns an ostream&
, which allows you to write cout << a << b;
Upvotes: 1
Reputation: 506847
The obvious return type is int&
:)
For increased elaboration:
int &operator[](ptrdiff_t i) { return myarray[i]; }
int const& operator[](ptrdiff_t i) const { return myarray[i]; }
// ^ could be "int" too. Doesn't matter for a simple type as "int".
Upvotes: 15