omi
omi

Reputation: 145

Overloading operator[] for a template class- c++

just wrote a code for a template array class (I know its not finished yet), and trying to remember how to overload operators (meanwhile without special difficulties...).

Anyway, while thinking of how to implement operator[] I wondered what would happen if the index is outside the boundaries of the array... I'm pretty sure it is not possible for me to return a NULL (because of the return type), right? and if so, what should I return in case the index is out of boundries?

here's the code, most of it is redundant to my question, but it might help anyone who google's operators overloading so I post the complete code...

#ifndef __MYARRAY_H
#define __MYARRAY_H

#include <iostream>
using namespace std;

template <class T>
class MyArray
{
    int phisicalSize, logicalSize;
    char printDelimiter;
    T* arr;

public: 
    MyArray(int size=10, char printDelimiter=' ');
    MyArray(const MyArray& other);
    ~MyArray() {delete []arr;}

    const MyArray& operator=(const MyArray& other);
    const MyArray& operator+=(const T& newVal);

    T& operator[](int index);

    friend ostream& operator<<(ostream& os, const MyArray& ma)
    {
        for(int i=0; i<ma.logicalSize; i++)
            os << ma.arr[i] << ma.printDelimiter;
        return os;
    }
};

template <class T>
T& MyArray<T>::operator[]( int index )
{
    if (index < 0 || index > logicalSize)
    {
        //do what???
    }

    return arr[index];
}

template <class T>
const MyArray<T>& MyArray<T>::operator+=( const T& newVal )
{
    if (logicalSize < phisicalSize)
    {
        arr[logicalSize] = newVal;
        logicalSize++;
    }

    return *this;
}

template <class T>
const MyArray<T>& MyArray<T>::operator=( const MyArray<T>& other )
{
    if (this != &other)
    {
        delete []arr;
        phisicalSize = other.phisicalSize;
        logicalSize = other.logicalSize;
        printDelimiter = other.printDelimiter;
        arr = new T[phisicalSize];

        for(int i=0; i<logicalSize; i++)
            arr[i] = other.arr[i];
    }

    return *this;
}

template <class T>
MyArray<T>::MyArray( const MyArray& other ) : arr(NULL)
{
    *this = other;
}

template <class T>
MyArray<T>::MyArray( int size, char printDelimiter ) : phisicalSize(size), logicalSize(0), printDelimiter(printDelimiter)
{
    arr = new T[phisicalSize];
}

#endif

Upvotes: 0

Views: 974

Answers (1)

Yuushi
Yuushi

Reputation: 26040

operator[] generally does no bounds checking. Most of the standard containers that can have a range utilize a separate function, at(), which is range checked and throws a std::out_of_range exception.

You likely want to implement a const T& operator[] overload, too.

Upvotes: 6

Related Questions