Custom assignment to lvalue of overloaded [] (array) operator

Hi

I'm currently trying to learn C++. I'm at the chapter on operator overloading and I have a question.

I've implemented a custom array class, MyEvenArray, and I've overloaded the [] operator as usual so that it returns a reference to an element of MyEvenArray. Now I'm curious if there's any way to overload the assignment TO said reference to allow for validation. The answer may well be, "No, that's impossible!" but I thought I'd ask.

To clarify, let's say my class code is as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// MyEvenArray, an array that only lets you add even numbers
MyEvenArray {
    public:
           
        ...

        int& operator[] (int index) {
            return internalArray[index];
        }

        void setElement(int index, int element) {
            if(element % 2 == 0) {
                internalArray[index] = element;
            }
        }
    private:
        int internalArray[5];
};


Now, is there any way to do

1
2
MyEvenArray m();
m[0] = 3;


and have it fail as per the rules laid out in the setElement(int index, int element) function? I.e., can I have m[0] = 3 be equivalent to m.setElement(0,3) ?

I realize I could have internalArray be an array of MyEvenInts which have some special behaviour, but assuming I keep internalArray as an array of ints, is there any way to do what I want?
closed account (zb0S216C)
janetmweiss wrote:
"I realize I could have internalArray be an array of MyEvenInts which have some special behaviour, but assuming I keep internalArray as an array of ints, is there any way to do what I want?"

No, not without some devious, non-portable trickery. What you're asking for is to intercept the assignment between "M0" and the number 3 in order to determine if the right-hand side of the assignment is even before the assignment takes place; this isn't standard behaviour and is not supported.

Wazzak
Okay! Just curious :) Thanks.

In the continuing interest of my curiosity, do you think you could allude (briefly; I don't need enough details to actually implement it) to the non-portable trickery you mention?
you could return a proxy, like bitset and vector<bool> do
Cubbi, yeah, that was more or less what I meant when I said "I could have internalArray be an array of MyEvenInts which have some special behaviour" -- I just didn't know the right words for it. But then I have to implement all kinds of behaviour for the proxy class, which I don't feel like bothering with. So, to anyone who comes to this page in desperate need of a solution to my problem: Cubbi's would work. For my own purposes, looking at this as an academic exercise, I don't want to take that easy (if tedious) out :)
Topic archived. No new replies allowed.