difference between bracket operator [] and its constant version

P

puzzlecracker

In the following example,

String s;

std::cout<<s[3];
s[3]='x';


How does a compiler know which one to call? Does it try to call const
first, and if it fails it rolls back to non-const one. As is
cout<<s[3], How does it know which one to call?

Thanks
 
A

Alan Woodland

puzzlecracker said:
In the following example,

String s;

std::cout<<s[3];
s[3]='x';


How does a compiler know which one to call? Does it try to call const
first, and if it fails it rolls back to non-const one. As is
cout<<s[3], How does it know which one to call?

Both of those cases will call the non-const version of operator[] in
your 'String' class. (Assuming such a thing exits in this 'String' class).

to call the const one explicitly:

const String &cs = s;
std::cout << cs[3]; //can only match the const one.

Alan
 

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

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top