Making own array class

I need to make a class called myArray that can start from any index, including negative numbers. Basicly solving the array index out of bounds problem, and i was wondering if i can get ideas on how to even start this. I can do the basic stuff like printing the array out and overloading but i'm not sure on how to start making the class functional.
Do you know how to write a basic class? If not:
http://www.cplusplus.com/doc/tutorial/classes/
http://www.cplusplus.com/doc/tutorial/classes2/

Do you know how to write a template (in this case a class template)? If not:
http://www.cplusplus.com/doc/tutorial/templates/

Here's a crude start, applying the above:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
template <typename ElementType>
class MyArray
{
private:

    ElementType *p;
    unsigned int size;

public:

    // overloaded operator[]
    ElementType & operator [] (int i)
    {
        // ADD BOUNDS CHECKS!
        return p[i];
    }

    // overloaded operator[], for const operations
    const ElementType & operator [] (int i) const
    {
        // ADD BOUNDS CHECKS!
        return p[i];
    }
};


Of course, there's a huge amount of work that remains to be done before the above becomes a usable class.
Thank you so much this is a huge help!!!
so if I'm understanding correctly the code you posted saves a number to the array index? is that correct? if so that was my biggest problem to solve and you've made this much less stressful
so if I'm understanding correctly the code you posted saves a number to the array index?

No. The code I posted above is an unfinished class template. It is not usable yet.

The weird looking functions defined inside are the overloaded operator[].
This must be done in order for the below to compile:

1
2
3
4
5
MyArray<int> mi; // note that we specify ElementType as int

// ...

mi[0] = 98; // this would not work without overloading operator[] 

Topic archived. No new replies allowed.