1

I am learning about operator overloading in C++. To try it out, I overloaded the [] operator to print the value at the index given. The code worked when I defined the operator overload member function as public.

However when I tried to do the same thing by defining the overload method as private, the code does not work. It does not even enter the operator overload method and skips it completely.

Can somebody please explain to me what am I doing wrong? Do operator overload methods have to be public only?

Here is my code:-

#pragma once
class NArray
{
public:
    NArray(int size=100);

    int getValueAt(int index);
    ~NArray();

    void test(int index);
    //int operator[](int index) const;

private:
    int sizeOfArray;
    int array[100];

    int operator[](int index) const;
};


#include "NArray.h"
#include <iostream>

using namespace std;

NArray::NArray(int size)
{
    if (size > 0 && size <=100)
        sizeOfArray = size;
    else
        sizeOfArray = 100;

    for (int i = 0; i < sizeOfArray; i++)
    {
        array[i] = i;
    }
}


int NArray::getValueAt(int index)
{
    if (index > 0 && index <sizeOfArray)
    {
        return array[index];
    }
    else
    {
        return -1;
    }
}

int NArray::operator[](int index)const
{
    if (index > sizeOfArray || index < 0)
    {
        cout << "Index out of bounds" << endl;
        return -1;
    }
    else
    {
        cout << array[index] << endl;
        return array[index];
    }
}

void NArray::test(int index)
{
    array[index];
}

NArray::~NArray()
{
}

#include <iostream>
#include "NArray.h"

using namespace std;

int main()
{
    int size = 0;
    int index = 0;

    cout << "Enter Array Size:" << endl;
    cin >> size;

    NArray arr(size);

    cout << "Enter Index:" << endl;
    cin >> index;

    //This works for the public operator method
    //arr[index];

    //This does not
    arr.test(index);

    getchar();
    return 0;
}

Thanks in advance.

IEEE754
  • 49
  • 1
  • 9

1 Answers1

4

test is not using NArray::operator [], it is accessing array directly. Try changing array[index]; to (*this)[index]; inside of NArray::test, and make it const while you're at it since it's not modifying anything:

void test(int index) const;

// ...

void NArray::test(int index) const
{
    (*this)[index];
}

Also, you have a bug in operator[]if (index > sizeOfArray || index < 0) should be if (index >= sizeOfArray || index < 0).

ildjarn
  • 62,044
  • 9
  • 127
  • 211
  • That worked! I will mark this as answer. Can you please explain what was wrong with array[index]? I did not understand that. – IEEE754 Feb 14 '15 at 23:04
  • @IEEE754 : There's nothing wrong with it, per se, except that it doesn't do what you said you wanted. – ildjarn Feb 15 '15 at 04:40