Search code examples
c++operator-overloadingconversion-operator

Conversion vs subscript operator overload for class wrapping an array


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?


Solution

  • 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;