operator difference

S

stef

Hello,
Could you tell me the difference between

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

and

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



Thanks...
 
V

Victor Bazarov

stef said:
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
 
T

Tomás Ó hÉilidhe

Victor Bazarov said:
stef said:
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;
 
A

Abhishek Padmanabh

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.
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top