operator difference

Discussion in 'C++' started by stef, Dec 13, 2007.

  1. stef

    stef Guest

    Hello,
    Could you tell me the difference between

    char &operator[](int idx)
    {
    return tab[idx];
    }

    and

    char operator[](int idx)
    {
    return tab[idx];
    }



    Thanks...
     
    stef, Dec 13, 2007
    #1
    1. Advertising

  2. stef wrote:
    > Could you tell me the difference between
    >
    > char &operator[](int idx)
    > {
    > return tab[idx];
    > }
    >
    > and
    >
    > char operator[](int idx)
    > {
    > return tab[idx];
    > }


    The sixth symbol, '&' (called "ampersand"). Makes the return
    value type different.

    V
    --
    Please remove capital 'A's when replying by e-mail
    I do not respond to top-posted replies, please don't ask
     
    Victor Bazarov, Dec 13, 2007
    #2
    1. Advertising

  3. "Victor Bazarov" <> wrote in comp.lang.c++:

    > stef wrote:
    >> Could you tell me the difference between
    >>
    >> char &operator[](int idx)
    >> {
    >> return tab[idx];
    >> }
    >>
    >> and
    >>
    >> char operator[](int idx)
    >> {
    >> return tab[idx];
    >> }



    The one that returns a reference can be used as an L-value (in an
    assignment for instance).

    my_obj[5] = 77;

    --
    Tomás Ó hÉilidhe
     
    Tomás Ó hÉilidhe, Dec 13, 2007
    #3
  4. On Dec 13, 10:47 pm, stef <> wrote:
    > Hello,
    > Could you tell me the difference between
    >
    > char &operator[](int idx)
    > {
    > return tab[idx];
    > }
    >
    > and
    >
    > char operator[](int idx)
    > {
    > return tab[idx];
    > }


    If they were members of a class - they would cause overload ambiguity.
    You would declare the second one as const member, and first one as non-
    const. That is how random access is implemented for std::vector/
    std::string etc. Of course, for them the argument idx is not a signed
    int. It would be their specific size_type, for example: implementation
    defined typedef for an unsigned integral type.

    The second one returns by value, so a copy is returned.
     
    Abhishek Padmanabh, Dec 14, 2007
    #4
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. jakk
    Replies:
    4
    Views:
    12,610
  2. Nick Timkovich
    Replies:
    0
    Views:
    84
    Nick Timkovich
    Feb 25, 2014
  3. Skip Montanaro
    Replies:
    0
    Views:
    83
    Skip Montanaro
    Feb 25, 2014
  4. Peter Otten
    Replies:
    1
    Views:
    102
    Mark Lawrence
    Feb 25, 2014
  5. Peter Otten
    Replies:
    0
    Views:
    74
    Peter Otten
    Feb 25, 2014
Loading...

Share This Page