1

Is it possible to call this member int MyClass::get(int key) const instead of the int& MyClass::get(int key)? In other words, where in the C++ source codes, a value can be used but not a reference?

#include <iostream>
using namespace std;

class MyClass {
public:
    MyClass(int input) : i(input) {};
    int i;

    int get(int key) const {
        std::cout << "int get(int key) const " << key << std::endl;
        return i; 
    }

    int& get(int key) {
        std::cout << "int& get(int key) " << key << std::endl;
        return i;
    }
};

void dummy(const int helpme)
{
    std::cout << helpme << std::endl;
}

int main() {
    // your code goes here
    MyClass abc(6);
    std::cout << abc.get(13) << std::endl;
    int result = (int)abc.get(16);
    dummy(abc.get(18));
    return 0;
}
Jonas
  • 6,915
  • 8
  • 35
  • 53
David Gu
  • 13
  • 2
  • Why have you got an old fashioned cast here `(int)abc.get(16)`? – Ed Heal Jan 19 '17 at 21:27
  • 3
    In C++17, you will be able to use `std::as_const( abc ).get(...)`. Otherwise, you can bind `abc` to a `const MyClass &`. Note that I do not encourage this kind of design, though – KABoissonneault Jan 19 '17 at 21:27

1 Answers1

3

The simplest solution is to use a const & to your variable. Two simple ways are

const auto & abc_const = abc;
std::cout << abc_const.get(13) << std::endl;

or

std::cout << static_cast<const MyClass&>(abc).get(13) << std::endl;

Edit: It looks like you were trying to choose an overload based on the return type, based on these two lines :

int result = (int)abc.get(16);
dummy(abc.get(18));

See this answer explaining how the return type is never used during overload resolution.

Community
  • 1
  • 1
François Andrieux
  • 28,148
  • 6
  • 56
  • 87