Thread: how to overload [] operator?

  1. #1

    how to overload [] operator?

    I don't understand how and why to overload the [ ] operator.
    Could someone please help me understand ?

  2. #2
    geek SilentStrike's Avatar
    Join Date
    Aug 2001
    Simple example, make a vector that has ranged checked indexing. This could be better done if it threw exceptions rather than exited when an out of bounds index was tried to be accessed, and if it was templated rather than just used for doubles. Nonetheless, it still illustrates the purpose of operator overloading. This new class will behave similair to an array, and the syntax for accessing elements is the same.
    class doubleVec {
    	double& operator[](int index);
    	doubleVec(int numElements);
    	doubleVec(const &doubleVec) { } // disallow copying
    	double* array;
    	int size;
    doubleVec::doubleVec(int numElements) {
    	array = new double[numElements];
    	size = numElements;
    doubleVec::~doubleVec() {
    	delete[] array;
    double&::operator[] (int index) {
    	if (index >= size) {
    		cerr << "Out of range, tried to access " << index << " max index is " << size - 1;
    	else if (index < 0) {
    		cerr << "Negative index of " << index;
    	else return array[index];
    I haven't debugged that code, but it's just for show purposes.
    Last edited by SilentStrike; 10-17-2001 at 05:47 PM.
    Prove you can code in C++ or C# at TopCoder, referrer rrenaud
    Read my livejournal

  3. #3
    thanks for your reply, I appreciated it.

  4. #4
    Join Date
    Aug 2001
    You should also overload the const and non-const operator[]'s as
    someone could write

    Vector A;

    A[4] = 4;


    const Vector A;

    if (A[4] == 4) do_something();

    With out the const overloaded someone using your class
    could run into trouble.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Failure to overload operator delete
    By Elysia in forum C++ Programming
    Replies: 16
    Last Post: 07-10-2008, 01:23 PM
  2. Smart pointer class
    By Elysia in forum C++ Programming
    Replies: 63
    Last Post: 11-03-2007, 07:05 AM
  3. Need help on understandind arrays
    By C++mastawannabe in forum C++ Programming
    Replies: 9
    Last Post: 06-16-2007, 10:50 PM
  4. operator overloading and dynamic memory program
    By jlmac2001 in forum C++ Programming
    Replies: 3
    Last Post: 04-06-2003, 11:51 PM
  5. Overloading the [] operator trouble
    By rmullen3 in forum C++ Programming
    Replies: 2
    Last Post: 08-01-2002, 12:46 PM