Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the compiler decide which function to call?

supposed there are two overloaded member function(a const version and a non-const version) in the String class:

char & String::operator[](int i)         //Version 1
{
    cout<<"char & String::operator[](int i) get invoked."<<std::endl;
    return str[i];
}


const char & String::operator[](int i) const       //Version 2
{

    cout<<"const char & String::operator[](int i) const get invoked."<<std::endl;
    return str[i];
}

and there is a test code fragment

int main(){
    String a;
    cout<<a[0]<<endl;  //Line 1
    a[0]='A';     //Line 2
}

How does the compiler decide which function to call? I found that Version 1 always got called when I run the program. Could anybody tell me why it is? And how can Version 2 got called?

like image 324
JDein Avatar asked Apr 21 '12 14:04

JDein


2 Answers

If a is const, the second overload will get called.

int main(){
    const String a;
    cout<<a[0]<<endl;   // would call const version
    a[0]='A';           // will not compile anymore
}
like image 128
Luchian Grigore Avatar answered Nov 13 '22 15:11

Luchian Grigore


If the object is const, the the const member function will be called. If the object is non-const the non-const member-function is called.

Exception
If their is only the const function, it is called in any case.

#include <iostream>
using namespace std;

class Foo {
public:
    void print() {
        cout << "Foo non-const member function\n";
    }
    void print() const {
        cout << "Foo const member function\n";
    }
};

class Bar {
public:
        void print() const {
                cout << "Bar const member function\n";
        }
};


int main() {
    Foo foo_non_const;
    const Foo foo_const;

    Bar bar_non_const;
    const Bar bar_const;

    foo_non_const.print();
    foo_const.print();

    bar_non_const.print();
    bar_const.print();

    return 0;
}

$ ./blah

Foo non-const member function
Foo const member function
Bar const member function
Bar const member function
like image 40
Peter Avatar answered Nov 13 '22 16:11

Peter