r xu r xu - 17 days ago 5
C++ Question

define operator[] for assignment and for reading

Is it possible to have two definition of

for the following two cases?

  • My_bit_array[7] = true;

  • bool x = My_bit_array[0];

This is useful because reading a bit and toggling one of the 8 bits of a byte (
) are different. These two cases would require two different definitions.


you can overload subscript operator "[]" to return the address of element to be able to assign to and you overload it to print the element in array just const this in order not to be able change it:

#include <iostream>
using namespace std;

class Byte
        Byte(bool[], int);
        ~Byte() {delete[] itsBits;}

        bool& operator[](int);
        const bool operator[](int)const;

        bool* itsBits;
        int  itsLength;

Byte::Byte(bool bits[], int length) : 
    itsBits = new bool[itsLength];
    for(int i(0); i < itsLength; i++)
        itsBits[i] = bits[i];

bool& Byte::operator [](int index)
    if(index < 0 || index > itsLength)
        return itsBits[0];
        return itsBits[index];

const bool Byte::operator [](int index)const
    if(index < 0 || index > itsLength)
        return itsBits[0];
        return itsBits[index];

int main()

    bool bArray[] = {true, false, true, true, false, true, false, true};
    Byte theByte(bArray, 8);

    cout << theByte[2] << endl;

    theByte[2] = true; // invoking bool& operator[] it returns a reference the 3rd element in array so we can assign to it value

    cout << theByte[2] << endl; // invoking const bool operator[]const just for printing not assigning

    cout << theByte[6] << endl; // the same as above

    cout << endl << endl << endl;
    return 0;