2

I have a class wrapping an array and want to provide the typical subscript access to its users.

...
class C;
C c;
auto x = c[0];
...

I may both provide conversion

class C
{
    int i[10];
public:
    operator int*() { return i; }
};

and provide subscript operator overload

class C
{
    int i[10];
public:    
    int& operator[](unsigned idx) {
        // eventual out-of-bounds check
        return i[idx]; 
    }
};

Apart from OOB check, which one should be preferred?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
user1832484
  • 371
  • 3
  • 8
  • 1
    Prefer `operator[]`. See this related [question](https://stackoverflow.com/questions/59076004/why-stdstring-does-not-have-const-char-cast) for reasons why. – Evg Nov 28 '19 at 10:47
  • _Apart from OOB check_ OOB = out-of-bounds? Range check (maybe, in debug only like in common `std::vector::operator[]` implementations) alone is worth to prefer the latter. ;-) – Scheff's Cat Nov 28 '19 at 10:52

1 Answers1

3

If you just want to call operator[] on the class C, then just overload operator[]. Don't allow implicit conversion if not necessary. If you provide operator int*, something meaningless and dangerous will be allowed too. e.g.

C c;
if (c) ...;
delete c;
songyuanyao
  • 169,198
  • 16
  • 310
  • 405