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?

2
  • 1
    Prefer operator[]. See this related question for reasons why. Commented Nov 28, 2019 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. ;-) Commented Nov 28, 2019 at 10:52

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

2 Comments

Don't allow implicit conversion if not necessary. I just remembered how often I add explicit to constructors to satisfy my paranoidity, and spent +1. ;-)
@Scheff It's worthwhile, definitely. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.