0

What are the differences between the following two implementations for accessing a private constant class member?

// Auto& (compile ok)
class Foo {
  private:
    const int _foo;
  public:
    Foo(const int& in) : _foo(in) {}
    auto& foo() { return _foo; }
}

// Explicit type (compiler error)
class Foo {
  private:
    const int _foo;
  public:
    Foo(const int& in) : _foo(in) {}
    int& foo() { return _foo; }
}

With auto the compiler does not complain but the explicit int type declaration in fact gives compiler error (which is due to the constness). In this case, what is auto deduced?

ildjarn
  • 62,044
  • 9
  • 127
  • 211
Jes
  • 2,614
  • 4
  • 25
  • 45
  • Sidenote: Be sure you know what you're doing w.r.t. semantics when using const references. See [int vs const int&](http://stackoverflow.com/a/4705871/211160). And notice it could well be slower than returning an int. – HostileFork says dont trust SE Apr 12 '16 at 04:51

1 Answers1

4

Since _foo is of type const int, auto refers to const int. Change your 'Explicit type' code to return const int& and the compiler should not complain anymore.

CantrianBear
  • 1,013
  • 1
  • 12
  • 22