const vs const&

E

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)?
 
S

Sylvester Hesp

ek said:
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
 
S

Stefan Naewe

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.
 

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
474,294
Messages
2,571,511
Members
48,212
Latest member
SteveMagga

Latest Threads

Top