Jim
Jim

Reputation: 171

C++ Subscript operator

I have written a code but it doesn't seems to work. Every time I execute the program, I get this error

Run-Time Check Failure #2 - Stack around the variable 'ary' was corrupted

anyway here is my code(it is a small code)

#include <iostream>
using namespace std;

class Arrayz{
private:
    int arry[5];
public:
    Arrayz(){}
    void setInf(){
        for(int i = 0; i < 5; ++i){
            cout << "Enter age of your friends: ";
            cin >> arry[5];
        } 
    }
    const int& operator [](const int pos){
        return arry[pos];
    }
};

int main(){
    Arrayz ary;
    ary.setInf();
    cout << "Here are your friend's age: " << endl;
    for (int i = 0; i < 5; ++i){
        cout << ary[i] << endl;
    }


    return 0;
}

also can you also help in subscript operator, I just don't seem to understand how to declare and use them. Also it seems pretty foolish to write a program without first understanding it first but anyway help would be appreciated :)

Upvotes: 0

Views: 417

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

You made a typo in member function setInf. Instead of cin >> arry[5]; there shall be cin >> arry[i];

void setInf(){
    for(int i = 0; i < 5; ++i){
        cout << "Enter age of your friends: ";
        cin >> arry[i];
    } 
}

As for the subscript operator then you defined it correctly

const int& operator [](const int pos){
    return arry[pos];
}

though there is no need to declare the parameter with qualifier const. Also the operator itself should have qualifier const You could write simply

const int& operator [](int pos) const {
    return arry[pos];
}

Or

int operator [](int pos) const {
    return arry[pos];
}

Also you could define its non-const version when the user could change elements of the array arry.

int & operator []( int pos) {
    return arry[pos];
}

Also it is a good idea that your class had a member function that would return the size of the array. For example

class Arrayz{
private:
    static const size_t N = 5;
    int arry[N];
public:
    Arrayz(){}
    void setInf(){
        for(int i = 0; i < N; ++i){
            cout << "Enter age of your friends: ";
            cin >> arry[i];
        } 
    }
    int operator [](int pos) const {
        return arry[pos];
    }

    int & operator []( int pos) {
        return arry[pos];
    }

    size_t size() const { return N; }
};

And in main you could write

for (int i = 0; i < ary.size(); ++i){
    cout << ary[i] << endl;
}

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 477000

You probably mean cin >> arry[i];i, not 5.

Upvotes: 5

Related Questions