1

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?

Marvin
  • 285
  • 2
  • 16
  • 1
    You should make the vector elements be a class, then you can overload the assignment operator to check the values. – Barmar Mar 26 '16 at 00:51
  • 1
    If I understand correctly, you are asking to create a class/struct (let's say class ValType) inside the class Poly and then the vector elem should hold values of type ValType. When the operator [] is used, I should then return the class and let operator= take care of the assignment? Is it similar to use of proxy class as in http://stackoverflow.com/a/7411385/2674424 ? – Marvin Mar 26 '16 at 17:41
  • Yes, that looks similar. – Barmar Mar 27 '16 at 03:51

1 Answers1

2

No, you cannot achieve that. By using operators you have to expose a reference to the variable if you want to assign a value to it. There is no function call involved in this process, it is being held by providing place in memory where the value is actually stored.

bottaio
  • 4,963
  • 3
  • 19
  • 43