Still need some help understanding how to properly overload "[]"

In order to call a function that overloads the "[]" operator, do I have to pass the subscript of an array of class objects? or can it be any type of array?

The code below is just some experiment I have been doing to understand overloading operators, but in lines 46 and 49 i have some trouble understanding (due to voodoo coding) what exactly is going on.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
#include <cstdlib>

using namespace std;

class Plant
{
    int *pointer;
    int num_of_elements;

public:

    Plant (int sub)
    {
        num_of_elements = sub;
        pointer = new int [num_of_elements];

        for (int n = 0; n < num_of_elements; n++)
        {
            pointer [n] = (n * 5);
        }
    }



    int &operator [] (int sub)
    {
        if (sub < 0 || sub >= num_of_elements)
            {
              cout << "Error, no subscript found" << "\n";
            exit(0);
            }

        else
            return pointer[sub];
    }
};

int main ()
{

    Plant array(5);

    for (int n = 0; n < 5 ; n++)
    {
        array[n] = (n * 2);    //by the way, does the class object "array" get converted to an actual array in this statement?
    }

    cout << array[3];     //Can I only pass an array of class objects?

}
Last edited on
Topic archived. No new replies allowed.