0

I'm writing a dynamic array class. I've overloaded the operator[] to access the pointer containing the data in my array. Also in my class is a member size denoting the number of objects in the array. I need to be able to add elements by assigning them via A[i] as well as add to front or end using member functions. The problem is that when assigning using A[i] = x, I don't know to increment size. Is there a way to distinguish whether the [] operator is being used on the left side of = as opposed to simply accessing that index? I've included a simplified version of my implementation.

using namespace std;
#include <iostream>
class Array
{
    public:
        [constructors, destructor];
        int& operator[](int index);
        [addToFront(),addToBack(), etc.]
    private:
        int size;     // holds the number of objects in the array
        int capacity;
        int* arr;     // ptr to the data in the array
}

int& Array::operator[](int index)    // overloaded array access operator
{
    return arr[index]; // simplified version of what I use
}

int main()
{
    Array A(6);    // initialize capacity using parameterized constructor
    A.addToFront(15); // addToFront() is able to increment size inside of its function
    A[1] = 10;    // How can I know that I am adding a new object to the array
    return 0;
}

Thanks!

Tanner Causey
  • 17
  • 1
  • 8
  • Instead of returning `int&`, return some sort of proxy/wrapper that overloads `operator=`. Not sure this is a good idea though, [it's easy to get into a horrendous mess that works almost but not *quite* like a normal container.](https://stackoverflow.com/q/17794569/1171191) – BoBTFish Sep 30 '19 at 07:04

1 Answers1

0

This can be done with a proxy object. You can overload an operator = for these objects and do more complicated stuff like incrementing size within that member function. Example:

class Array
{
   // Rest as before...

   struct Proxy {
     Array& ref;
     int pos;

     Proxy& operator =(int n)
     {
        ref.arr[pos] = n;
        ++ref.size;

        return *this;
     }
   };

   Proxy operator[](int index);
};

The implementation of operator[] would then be

Array::Proxy Array::operator[](int index)
{
   return Proxy{*this, index};
}

and the usage as you showed in the exemplary snippet.

lubgr
  • 37,368
  • 3
  • 66
  • 117