I have created a class Poly
in C++, which has the private members as defined below.
private:
std::size_t sz;
std::vector <T> elem;
What is the standard way of overloading assignment operator and/or subscript operator to assign value to an element of a container? For example:
Poly < double > obj{1, 2, 3};
obj[1] = 1;
should assign the value 1 to the second element.
One way to implement this maybe:
T & operator[](int i) {
if(i < 0 || i >= sz)
throw std::out_of_range{"Poly::operator[]"};
return elem[i];
}
However, this returns the element by reference and the assignment is done outside the class, as opposed to being done by a member function. Does it not violate the principle of abstraction as the private members are being accessed outside the object? Moreover, one cannot ensure the checking of the invariants, i.e., let's say we had a restriction on the value that could be assigned.
I would rather prefer having a member function such as:
void assign_val(T val, int idx)
{
//Check if the conditions hold...
//...
elem[idx]=val;
}
For subscript reading:
const T & operator[](int i) const{
if(i < 0 || i >= sz)
throw std::out_of_range{"Poly::operator[]"};
return elem[i];
}
Can something to this effect be obtained using operator overloading?