Question about operator overloading

R

Rafael Anschau

In this case, how does the compiler knows which to run, given
that both operators receive the same parameter ?


class String
{
// overloaded operators
char & operator[](int offset);
char operator[](int offset) const;

//Which one gets runed ? If not based on parameters then based on
what ?


};

Thanks
 
K

Kai-Uwe Bux

Rafael said:
In this case, how does the compiler knows which to run, given
that both operators receive the same parameter ?


class String
{
// overloaded operators
char & operator[](int offset);
char operator[](int offset) const;

//Which one gets runed ? If not based on parameters then based on
what ?

In the expression str[index], index is a visible parameter to operator[],
but str also enters the picture. If str is a const object, then the const
member function will be chosen; and if str is non-const, the non-const
member function will be chosen.


Best

Kai-Uwe Bux
 
R

Rafael Anschau

Interesting, the only semantic description I have for const(after
a method) is that it doesn´t change the object´s member data. Are
there other places where const may have other meanings(aside from data
types
like "const int a=10;" etc, and operators) ?

Thanks,

Rafael
 
L

lunar_lty

In this case, how does the compiler knows which to run, given
that both operators receive the same parameter ?

class String
 {
  // overloaded operators
 char & operator[](int offset);
 char operator[](int offset) const;

//Which one gets runed ? If not based on parameters then based on
what ?

};

Thanks


The compiler will do the corrent thing for you.
Augument liks this :
String s("aa");
char c = s[0]; // call char operator[](int offset) const;
s[0] = 'c'; // call char & operator[](int offset);

That is the difference you want.
 
J

James Kanze

Interesting, the only semantic description I have for const(after
a method) is that it doesn´t change the object´s member data. Are
there other places where const may have other meanings(aside from data
types like "const int a=10;" etc, and operators) ?

const is part of the type system, and plays a defined role
anywhere types are significant.
 

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,774
Messages
2,569,598
Members
45,151
Latest member
JaclynMarl
Top