469,582 Members | 2,300 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,582 developers. It's quick & easy.

const vs const&

ek
This first example does not work (cannot be overloaded):

int& operator()(int a) { // (1)
return a;
}

int const& operator()(int a) { // (2)
return a;
}

but if I change (2) to (3):

int operator()(int a) const { // (3)
return a;
}

it works (overloading works). But why does (2) not work before I
change it to (3)?

May 16 '07 #1
2 1966

"ek" <ek*****@yahoo.comwrote in message
news:11**********************@p77g2000hsh.googlegr oups.com...
This first example does not work (cannot be overloaded):

int& operator()(int a) { // (1)
return a;
}

int const& operator()(int a) { // (2)
return a;
}
Indeed, you can't overload based solely on return type. Besides, the both
yield undefined behaviour because you're returning a reference to a local
variable, but I know that's not your point ;)
but if I change (2) to (3):

int operator()(int a) const { // (3)
return a;
}

it works (overloading works)
Because (3) only works on a const *this, whereas (1) also works on a
non-const *this.

struct A
{
void func();
void func() const;
}

int main()
{
A a;
const A ca;

a.func(); // calls void A::func()
ca.func(); // calls void A::func() const
}

- Sylvester
May 16 '07 #2
On 5/16/2007 2:06 PM, ek wrote:
This first example does not work (cannot be overloaded):

int& operator()(int a) { // (1)
return a;
}

int const& operator()(int a) { // (2)
return a;
}
You can't overload on return type only. Make (2):

int const& operator()(int a) const {
return a;
}

but if I change (2) to (3):

int operator()(int a) const { // (3)
return a;
}

it works (overloading works). But why does (2) not work before I
change it to (3)?
S.
--
Stefan Naewe
stefan dot naewe at atlas-elektronik dot com
May 16 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

20 posts views Thread by christopher diggins | last post: by
12 posts views Thread by zealotcat | last post: by
6 posts views Thread by p|OtrEk | last post: by
reply views Thread by tom olson | last post: by
8 posts views Thread by vsgdp | last post: by
13 posts views Thread by dragoncoder | last post: by
2 posts views Thread by nassim.bouayad.agha | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.