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!