5

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?

2 Answers 2

7

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
}
2

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
1
  • By the way, how can a non-const object invoke the const function?
    – JDein
    Apr 25, 2012 at 9:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.