3

If I have the following:

class A {
    int foo() const {
       j++;
       return i;
    }

    int& foo() {
       return i;
    }

    int i;
    mutable int j;
};

then obviously something like

A a;
a.foo() = 5;

calls the non-const version. But what conditions need to be met to make sure that a call is to the const or non-const version for a few examples...

int i = a.foo(); //I would expect to call the const. Is it guaranteed?

const int j = a.foo(); //Ditto

const int& l = a.foo(); //Ditto

int& k = a.foo(); //I would expect the non-const
foobar(k); //foobar is "void foobar(int)"
return; //but the compiler could potentially decide the const version is fine.
patros
  • 7,719
  • 3
  • 28
  • 37
  • `mutable` = yuck. EDIT but then I found this http://stackoverflow.com/questions/105014/c-mutable-keyword – rubenvb Apr 07 '11 at 17:50

4 Answers4

4

const function gets called when the object itself is const.

int i = static_cast<const A>(a).foo(); //calls const function

Also see this code for better understanding: (must read the comments)

void f(const A &a) //a is const inside the function
{
    int i = a.foo(); // calls const function
}
void h(A &a) //a is non-const inside the function
{
    int i = a.foo(); // calls non-const function
}

A a;
f(a);
h(a); //pass the same object!

See the online demo : http://ideone.com/96flE

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • 2
    I think that the cast should be `static_cast(a)`, else the static cast will create a copy of `a` that is const and then call the member on that copy. – David Rodríguez - dribeas Apr 07 '11 at 19:10
  • @David but if he casts to a reference, the object itself will still be non-const. He says "when the object itself is const", so the cast to a reference type would not correctly reflect his statement. – Johannes Schaub - litb Apr 07 '11 at 19:12
3

The constness of a decides which function - what you do with the return value is not a part of overload resolution. All your samples would call the non-const version.

Erik
  • 88,732
  • 13
  • 198
  • 189
3

Return values are never considered when determining which overload to take.

Also, when a is declared as

A a;

then the non const version takes precedence.

If a is declared as

const A a;

then the const version can be called only.

Alexandre C.
  • 55,948
  • 11
  • 128
  • 197
1

Whether your member function call resolves to a const member function or not, depends on the constness of the "this" pointer i.e. the object on the LHS of dot or arrow operator that is implicitly passed to the called member function.

Resolves to non const:

A a;
a.foo();

Resolves to const:

void bar(const A& a)
{
   a.foo();
}
ryaner
  • 3,927
  • 4
  • 20
  • 23