I do not understand "foo.get() = 15" in the code.

I do not understand foo.get() = 15;

as the function get has no parameter, what does foo.get() = 15; mean?
and why it returns 15?

Thanks in advance for any reply.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// overloading members on constness
#include <iostream>
using namespace std;

class MyClass {
    int x;
  public:
    MyClass(int val) : x(val) {}
    const int& get() const {return x;}
    int& get() {return x;}
};

int main() {
  MyClass foo (10);
  const MyClass bar (20);
  foo.get() = 15;         // ok: get() returns int&
// bar.get() = 25;        // not valid: get() returns const int&
  cout << foo.get() << '\n';
  cout << bar.get() << '\n';

  return 0;
}
.get() returns a ref to x. This is set to 15 which means that x is set to 15. Any change to the value of a ref changes the data to which the ref refers.

The get() member functions return a reference to your class' data member (x). The non-const get() version allows the class data member to be modified by assigning a different value to it.
@seeplus @Furry Guy
thanks for your replies.
Registered users can post here. Sign in or register to post.