patros
patros

Reputation: 7819

Is C++ guaranteed to call a certain constness of member function?

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.

Upvotes: 3

Views: 164

Answers (4)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361342

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

Upvotes: 4

ryaner
ryaner

Reputation: 3997

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();
}

Upvotes: 1

Alexandre C.
Alexandre C.

Reputation: 56956

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.

Upvotes: 3

Erik
Erik

Reputation: 91270

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.

Upvotes: 3

Related Questions