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.