0

i'm learning c++ and i try to know if its possible to use assignment = operator after call of operator []

I have an array class with private int *_content data, and the operator = overloaded. His constructor alloc my _content by the size passing in parameter.

My class looks like :

class Array {

private:
    int *_content;

public:    
    Array(unsigned int n) {
        this->_content = new int[n];
    }

    ~Array() {
            delete[] _content;
    }

    int operator[](int n) const {
        return this->_content[n];
    }
};

i can write the following code :

int main() {
    Array a(10);

    std::cout << a[5] << std::endl;
    return 0;
}

result :

0

I would like to know if it's possible to assign at the case n of my content by any operator after using [] like this :

a[5] = 2000;

And know if there is any clean solution in my case for this situation. Thank you for reply

Mark B
  • 95,107
  • 10
  • 109
  • 188
VelocityPulse
  • 613
  • 7
  • 13

4 Answers4

5

Yes, to do that you need to provide a version of [] that returns a reference to an element in the container:

int& operator[](int n) {
    return this->_content[n];
}

You can then modify the array element via that reference, with the exact syntax you propose at the calling site.

Other things going forward: You'll need to define an assignment operator and a copy constructor too. We call this "the rule of three". See What is The Rule of Three?. And it might be an idea to capture the size of the container passed on construction. You could then check if the n passed to the [] overload is within the bounds of the backing array.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • 1
    Yeah i think you speak about canonical coplien form that i just remove for this question. Thank you for the link and i will read this now ;) – VelocityPulse Jan 17 '18 at 14:56
  • Anyway the idea to capture the size is obvious and again remove for the question – VelocityPulse Jan 17 '18 at 14:58
  • 1
    @ClémentChameyrat: Awesome. I've mentioned them for the benefit of other readers, not necessarily you. And I like the term "Coplien Form", although personally I don't subscribe to it (due to the explicit destructor). – Bathsheba Jan 17 '18 at 15:00
4

At least you can overload the operator [] the following way

const int & operator[]( size_t n) const 
{
    return this->_content[n];
}

int & operator[]( size_t n) 
{
    return this->_content[n];
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

Make your operator[] return a reference, then you can assign to the returned value:

int& operator[](int n) {
    return this->_content[n];
}

then you can write

a[5] = 100;
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
0

of course, its possible, just let operator[] returns int&

```

int& operator[](int n) const {
    return this->_content[n];
    }

```

then

int main() {
    Array a(10);
    a[5]=1;
    std::cout << a[5] << std::endl;
    return 0;
}
Daniel
  • 391
  • 4
  • 8