const member function

I am wondering why the const member function .get() has to return a const value, and need to pass by reference. For example, int get() const {return x;} won't work. Thanks for any ideas.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  #include <iostream>
using namespace std;

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

void print (const MyClass& arg) {
	cout << arg.get() << endl;
}

int main() {
	MyClass foo(10);
	print(foo);
}
.
Last edited on
> For example, int get() const {return x;} won't work
it does work.
if your code is giving you errors, then post the code that gives you errors, along with the error message.
Topic archived. No new replies allowed.