Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overload resolution in C++

In Page 562 The C++ Programming Language 4e, the author shows two functions:

char& operator[](int n) {}
char operator[](int n) const {}

If I write

char c = someObj[2];

Since the resolution didn't take care of the return type, and then, which function will be chosen?

I made several tries and it just to call char& operator[](int n) {}, and I think the const function defined here just to give it a chance to be able to be called in some context that require a const. But I not quite sure that.

this is my testing code:

#include <iostream>
using namespace std;

class A {
private:
    char p[10] = "abcdefg";
public:
    char operator[](int n) const {
        cout << "const function" << endl;
        return p[n];
    }
    char& operator[](int n) {
        cout << "plain function" << endl;
        return p[n];
    }

};

int main() {
    A a;
    a[2];
    const char &c = a[4];
}
like image 852
Jekton Avatar asked Feb 09 '23 07:02

Jekton


1 Answers

The return type is not considered in overload resolution. Your overload will be selected based on the const-qualification of the object the operator is called on:

int main() {
    A a;
    a[2];
    const char &c = a[4];

    const A b;
    b[2];
    const char &d = b[4];
}

The output of this is:

plain function
plain function
const function
const function
like image 86
TartanLlama Avatar answered Feb 24 '23 03:02

TartanLlama