Overloading [] and = operators to accept values for my template class in C++

Viewed 226

I am creating my own ArrayList STL class in C++ and now am stuck in a problem. I want to overload the [] or = operator (I'm sorry I don't know which one will be better implementation) such that the value on the right side of = operator gets assigned to the element of the vector accessed by the [] operator.

I have overloaded the [] operator to get the element from the array but don't know how to deal with assignment with it.

Here's the ArrayList class implementation :

template<class T> class ArrayList
{
   T* array;
   ArrayList() {}
   
   // Implemetation of [] overloading
   T& operator[] (int index) {return array[index];}
}
1 Answers

You are getting confused. You are asking about assigning T objects but T is not your ArrayList class. It's up to the T class to handle it's own assignment, not upto your ArrayList class.

The code you have written already will work fine.

ArrayList<int> x = ...;
x[1] = 2;

ArrayList<std::string> y = ...;
y[0] = "hello";

Although you should make the const change that Ted mentioned in the comments.

Related