Search code examples
c++operator-overloadingoverloadingsubscriptarray-indexing

Is it possible to overload [] operator to do different thing in C++


I want to overload "[]" witch is used to access array

But I also want to separate read/write to do different thing

For example :

class myclass{
private:
    int val;
public:
    myclass(){val=0;}
    myclass(int _in){val=_in;}
    ....
    //for A=myclass[n]
    myclass& operator[](int index){
        ...
        return 
    }
    //for myclass[n]=B
    myclass& operator[](int index){
        ...
        return 
    }
}

Solution

  • The chosen operator overload is affected solely by the type of the operands, and not how you use the returned value. There can only be one overload for one pair of operands.

    However, you can use a return value that behaves one way when used as left hand operand of assignment, and another way when used as right hand operand.