itzikos
itzikos

Reputation: 405

Calling const function from non-const object

i have a problem with function overloading while using const function and const object. Can someone explain why "const foo int& int" is being print instead of "foo int char&" in the following code?

struct A 
{
    void foo(int i, char& c) { cout << "foo int char&" << endl;}
    void foo(int& i, int j) const { cout << "const foo int& int" << endl;}
};

int main() {
    A a;
    const A const_a;
    int i = 1;
    char c = 'a';
    a.foo(i,i);
}

Thanks,

Upvotes: 0

Views: 990

Answers (4)

Vlad from Moscow
Vlad from Moscow

Reputation: 310920

There is all clear. You called a function with two arguments of type int. There are two function candidates. One that have the first parameter of type int and the second parameter of reference to char. So to call this function the second argument shall be implicitly converted to type char &. But it is a narrowing conversion because the rank of int is higher than rank of char. So a temporary object will be created but temporary object may only be binded with a const reference. The second function does not require any conversion of its arguments. So it will be called.

Upvotes: 2

The first function cannot be called with an int as the second argument. A char& cannot be bound to an int. That means that only the second overload is an alternative.

Upvotes: 1

michaeltang
michaeltang

Reputation: 2898

  1. define function as const means you cannot change the member variables in the object
  2. non const function cannot be called by const object
  3. A character, a short integer, or an integer bit-field, all either signed or not, or an object of enumeration type, may be used in an expression wherever an integer maybe used. If an int can represent all the values of the original type, then the value is converted to int; otherwise the value is converted to unsigned int. This process is called integral promotion

Upvotes: 0

Pavel Davydov
Pavel Davydov

Reputation: 3569

Cause void foo(int& i, int j) const is a better match, other function needs an int to char convertion.

Upvotes: 1

Related Questions