setter and getter function for an array

How do I return an element of an array using a setter or getter function?
I know that the following is the format for any data type:
----------------
void get_element()
{ return radius; }

void set_element(int radius)
{radius=r; }

----------------

Now what happens if my data type is an array element? How can i return or set the value of a particular array element? a for loop , may be?

void get_element(int i)
return array[i];

in this case, how will the program know what value of i was entered? I would want to put the setter/getter function in the class definition.

Please help me. Thank You.
Last edited on
n this case, how will the program know what value of i was entered?


What exactly do you mean by this?

In any case, I would override the subscript operator twice. Once as a const for read-only access and another for read and write access. You can also implement some out-of-bounds checking.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Foo& operator [] (int i) 
{
    if (i < 0 || i > MAX_SIZE)
        cout << "Array out of bounds!\n";
    else 
        return Foo[i]; 
}

Foo operator [] (int i) const
{
    if (i < 0 || i > MAX_SIZE)
        cout << "Array out of bounds!\n";
    else 
        return Foo[i]; 
}



I'm still not sure what you mean by how does the program know what you entered. You will pass in an integer as an index and your routine will simply return the value at that index.


Last edited on
For getter it is simply to do. You declare parameter that will specify element's index of array.

For example

int get_element( size_t index ) { return ( a[index] ); }

For setter you can specify two parameters: element's index and a new value

void set_element( size_t index, int value ) { a[index] = value; }

Also you can overload operator [] if your array is a part of a class definition.
Last edited on
icethatjaw,

Thanks. Great reply :)
What I mean is how will the program know which array element to read or write(get or set) ? LEt's say I enter i=3. so the array's 4th position gets read, but how will the program know this? should i pass this parameter?

yes, I could implement out of bounds checking - I never thought about that.

Also, what is this statement in your program - operatot [] ?? is it over loading?
vlad from moscow,
Awesome, thanks.


That was what I was wondering - if I should pass a parameter. I will try adding these changes, as mentioned by you. However, I'm not sure how to overload operators???

Yes, my array is part of a class definition.
I'm teaching myself basic data structures such as arrays and stacks. Not really got to the point where I would want to overload [].

What I mean is how will the program know which array element to read or write(get or set) ? LEt's say I enter i=3. so the array's 4th position gets read, but how will the program know this? should i pass this parameter?

yes, I could implement out of bounds checking - I never thought about that.

Also, what is this statement in your program - operatot [] ?? is it over loading?


It is up to you how to decide what to return. If you want int get_element(3) to return the 3rd value in the array you could simply add +1 to the index inside the routine. Otherwise it will return the 2nd value because you know that's how arrays work. Notice that get_element is an integer returning function. Whatever datatypes are stored in the array must be the datatype of the return value of that function. So if your array had strings you would obviously set get_element to return a string.

My answer was geared towards you having a class or struct. I apologize for assuming that. You can only overload the [] operator in a class or struct.

The statement "operator []" is referring to the subscript operator which is what you index arrays with.

Last edited on
I just made the changes as suggested here and realized that is is kind of " mandatory " that I overload the []. I keep getting an error that says" no match for []".

So I might have to do that anyway.
If you show me the source I can show the correct way to overload the [] operator.
What I'm trying to do is :
Design an array class. Allow the user to dynamically allocate memory for the array and also allow the user to view/write elements in a randam access manner.

Here is what I wrote so far:


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
class array{
    private:
        int size,input,user_array[5];
    public:
        array() {  //constructor to initialize array elements to zero in case user wants to
            for(int i=0;i<size;i++)
             user_array[i]=0;
            }
        array(int size){ //constructor to populate the array elements based on the values entered by the user
            for(int i=0;i<size;i++)
            user_array[i]=input;
        }
     //   ~array()
     //   delete pointer[];
        int read(int i)
        {return user_array[i];}
        void write(int i,int value)
        {user_array[i]=value;}
};


int main() {
     
     array obj1,obj2;
     int *ptr,j,k,n;
     cout<<" Number of elements?"<<endl;
     cin>>n;
     ptr=new int[n];
        int user_array[n];
        cout<<"Enter the values for your array of "<<n<<" elements"<<endl;
      for(int i=0; i<n; i++)
        cin>>user_array[i];
     cout<<"What element do you want to view?" <<endl;
     cin>>j;
     obj1[j].read(i);
     cout<<"What element do you want to write to?" <<endl;
     cin>>k;
     obj1[k].write(i);
     return 0;
    }
    


-----deleted-----
Last edited on
Here is my code for overloading [] . I do not know much about overloading, just browsed a few pages on the internet. am i correct here?
1
2
3
4
int &operator[](int sub) //overloading []
        { if(sub<0||sub>size)
        cout<<"Terminating program, wrong choice"<<endl;//bounds checking
        return user_array[sub];
Your constructors are invalid because neither class member size no class member input are initialized. So they have undefined behavior. Moreover using the constructor with parameter can result to memory overwrite, because you do not check value of size against fixed size of your array. So first of all you should rewrite your class.
You mean the code goes in the class definition? I have corrected my program here:

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
class array{
    private:
        int size,input,user_array[size];
    public:
        array() {
            for(int i=0;i<size;i++)
             user_array[i]=0;
            }
        array(int size, int input){
            for(int i=2;i<size;i++)
            user_array[i]=input;
        }
     //   ~array()
     //   delete pointer[];
        int read(int i)
        {return user_array[i];}
        void write(int i,int value)
        {user_array[i]=value;}
        int &operator[](int sub) //overlaoding []
        { if(sub<0||sub>size)
        cout<<"Terminating program, wrong choice"<<endl;
        return user_array[sub];
    }
};


int main() {
     
     array obj1;
     int *ptr,j,k,n;
     cout<<" Number of elements?"<<endl;
     cin>>n;
     ptr=new int[n];
     int new_array[n];
        cout<<"Enter the values for this sparse array of "<<n<<" elements"<<endl;
      for(int i=0; i<n; i++)
        cin>>new_array[i];
    cout<<"What element do you want to view?" <<endl;
    cin>>j;
     cout<<obj1.read(j);
   //  cout<<"What element do you want to write to?" <<endl;
   //  cin>>k;
   //  obj1[k].write(i);
     
     for(int i=0;i<n;i++)
     cout<<new_array[i];
     return 0;
    }


is this better? also, how can i make the array dynamic size, as you have mentioned?
I'm trying to change the program and make the array random read/write. LEt's say the user wants to re-write element[2]. So my write function is supposed to do this but the system throws an error : no match for operator <<
:(
what is going on here?
Instead of declaring a array at compile time why don't you just declare a pointer to whatever datatype you are storing in the array and then when you get the size from the user allocate one dynamically off the heap.

1
2
3
4
5
6
7
8
9
10
int size;
int* user_array;

cin >> size;

user_array = new int[size];

//In your destructor
delete[] user_array;
Last edited on
I see your point. but is this not similar to what I've done in the int main() ?
or shoudl I remove the array declaration from int main() and put it in the class definition(in the constructr may b?)

Last edited on
No it's not similar.

If you are not 100% sure of the size of an array at compile time then you should allocate it during run-time. You can accomplish this with a pointer and the keyword new.
So does this run-time allocation go in the int main() function or in the class definition?
It will either go in your main function or in one of your class methods. The pointer needs to be declared somewhere but the actual allocation with the keyword "new" is an instruction so it needs to occur in a function definition (code implementation), not a declaration (headers).

Last edited on
I got it-thanks

I will probably keep it in my main function.
Topic archived. No new replies allowed.