Subscript Functions

Hi :)

I need help understanding the subscript function in line 4 of the code. I know it is supposed to give element access, but I'm not sure how (what does elem[i] do... elem is not an array, right?!) An explanation of the return type, double&, would be very much appreciated too :)

1
2
3
4
5
6
7
8
9

1 class vector {
2      public:
3           vector(int s) : elem { new double[s] }, size{s} { }
4           double& operator[ ] ( int i ) { return elem[i]; }
5           int size( ) { return size; }
6      private:
7           double* elem;
8           int size;
Last edited on
Look up dynamic arrays.
1
2
3
Type *p = new Type[size]; //p points to first element of an array
*(p + i) = 7; //same as line 3
p[i] = 7; //same as line 2 
Last edited on
Topic archived. No new replies allowed.