0

Given a minimal example:

#ifndef ARR_H_
#define ARR_H_

#include <iostream>

class Array {
    public:
        Array();
        int operator[](int idx);
    private:
        int arr[10];
};

int Array::operator[](int idx) {
    std::cout << "ok";
    return arr[idx];
}

#endif

and I attempt to create an object

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

int main() {
    std::cout << "Create" << std::endl;
    Array obj();
    int i = obj[0];

    return 0;
}

Why do I get the error

main.cpp: In function ‘int main()’:
main.cpp:7:18: warning: pointer to a function used in arithmetic [-Wpointer-arith]
     int i = obj[0];
                  ^
main.cpp:7:18: error: invalid conversion from ‘Array (*)()’ to ‘int’ [-fpermissive]

Why does it not use my operator[]?

Syntactic Fructose
  • 18,936
  • 23
  • 91
  • 177

2 Answers2

1

This

Array obj();

is a function declaration that has no parameters and has return type Array.

Just write

Array obj;

Take into account that if you want to use the operator to assign values to the elements of the array then it is better when it returns reference to an element

int & operator[](int idx);

Also you could declare this operator for constant objects

const int & operator[](int idx) const;

or

int operator[](int idx) const;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

This is treated as a function declaration rather than object.

Array obj();

Replace with

Array obj;
Stas
  • 11,571
  • 9
  • 40
  • 58