Overloading [] operator

This is a discussion on Overloading [] operator within the C++ Programming forums, part of the General Programming Boards category; I was wondering how to overload the [] operator. A common example is this: Code: class myClass { int data[]; ...

  1. #1
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853

    Overloading [] operator

    I was wondering how to overload the [] operator. A common example is this:
    Code:
    class myClass
    {
       int data[];
       int maxSize;
       ....
       public:
         ...
          int &operator[] (int index) {
             if (index < maxSize)
                return data[index];
             else
               ...
            }
    }
    Why is the & for reference used? I don't fully understand the reason. What would be the difference by simply returning int?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    22,302
    Consider this expression: xyz[0] = 1;

    If operator[] returned by value, then the element of xyz at index 0 would not be changed to 1.

    Also, read this FAQ on const overloading as it applies to overloading operator[].
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    Just remember what a reference means. It means you are returning that specific variable instead of a copy of what that array element contains.

    You can do some other nifty stuff with that operator too.

    Example:
    Code:
    myclass &operator[](const std::string &name);

  4. #4
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    23,020
    Code:
    std::map<int, int> mymap;
    mymap[5] = 10; // What would happen here if mymap returns, say, char*?
    In the code above, the compiler will assign 10 to whatever is returned from mymap[5].
    So if mymap[5] returned char* instead of int&, what would happen? Compile error, and not something you'd expect!
    And if it merely returned int, the you would assign to a temporary!
    In other words, you don't make any change in the map at all.

    Code:
    class myClass
    {
        int data[];
        int maxSize;
        ...
    public:
        ...
        int& operator[] (int index)
        {
            if (index < maxSize)
                return data[index];
            else
                ...
        }
    };
    And please, write the class the right way
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  5. #5
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    Thanks for the replies. The right way you say? Are you referring to the public word, which shouldn't be in the same level with class?
    If that is the case, I would like to ask. You should write classes like:
    Code:
    class myClass
    {
       private:
            int a;
            int b;
        public:
            int c;
            int d;
    };
    If you don't use private, then int a, int b should be alligned with public or int c, int d?

  6. #6
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    23,020
    I changed public to the same level as the braces.
    I changed int &operator to int& operator.
    I also changed the indentation to be consistent (4 spaces everywhere; can't use tabs in the browser), instead of some spaces here and there.
    Also moved the opening brace down one line.

    Unfortunately, it's all about style
    I love this style, but others might not.
    But I insist that * and & binds to the type in C++ and not the name.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  7. #7
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    Oh, you changed it that is what got me confused, because I just thought you copy/pasted it. Lol. Yeah, mine was horrible and I have complaint about these things to a lot of people. Most of the codes I see have public in a different level from class, but again that is just style. I prefer the way you write it though, alligning it with class.

    As for * and &. Well, I agree that it makes more sense to think that when you declare a variable you have "type" "name". So the type should be like int*. If you write "type" "*name" then the type of the variable is a int*, even though you write int. And you mix information (that this is a pointer) with the name.

    What I don't like is having it in the middle. That is bad for me. Except for function declaration which is another story.

    On the other hand, it is more readable for me if you have it in front of the name. It looks "worse", but personally most of the times I don't care about whether the variable is int or long. That won't change the logic of the program most of the times. But if it is a pointer or a variable is important, it changes the logic. So I will most likely read only the name of the variable and not the type. At least at first glance. So having the * in front of the name helps me get that information right away.
    And... this has nothing to do with the subject which I created...

  8. #8
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    But I insist that * and & binds to the type in C++ and not the name.
    Wouldn't it be great if it did? Unfortunately, syntactically it doesn't, and putting the * and & to the name is a good way of reminding yourself of that little wart of the language.
    I still put it next to the core type in return types, though.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  9. #9
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    23,020
    Quote Originally Posted by CornedBee View Post
    Wouldn't it be great if it did? Unfortunately, syntactically it doesn't, and putting the * and & to the name is a good way of reminding yourself of that little wart of the language.
    I still put it next to the core type in return types, though.
    Yes, it would certainly be great, and dang it, how I wished they would allow it to actually bind to the type syntactically. But unfortunately it's a relic from C, not to mention how many people it would upset and how code it would break.
    Sometimes I wish C++ was more separated and strict from C and getting rid of old stuff and bad practices.
    Maybe someone will one day make C+++
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21