Problem with function argument

If i have this class for fractions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <cstdlib>
using namespace std;
// Models a mathematical rational number
class Rational {
	int numerator;
	int denominator;
public:
	// Initializes the components of a Rational object
	Rational(int n, int d) : numerator(n), denominator(d) {
		if (d == 0) {
			// Display error message
			cout << "Zero denominator error" << endl;
			exit(1); // Exit the program
		}
	}
	// The default constructor makes a zero rational number
	// 0/1
	Rational() : numerator(0), denominator(1) {}
	// Allows a client to reassign the numerator
	void set_numerator(int n) {
		numerator = n;
	}
	// Allows a client to reassign the denominator.
	// Disallows an illegal fraction (zero denominator).
	void set_denominator(int d) {
		if (d != 0)
			denominator = d;
		else {
			// Display error message
			cout << "Zero denominator error" << endl;
			exit(1); // Exit the program
		}
	}
	// Allows a client to see the numerator's value.
	int get_numerator() {
		return numerator;
	}
	// Allows a client to see the denominator's value.
	int get_denominator() {
		return denominator;
	}

};


Why cant i use const Rational& r as reduce funtion argument?
Its not like this get_numerator() method is going to change this object what im giving as argument

1
2
3
4
5
6
Rational reduce(Rational& r) {
	Rational reduced;
	int num = r.get_numerator(), den = r.get_denominator();
	...
	return reduced;
}


Its working as it is but i just want to know why i cant give this argument as const in case this would be a more serious project and i wouldnt want to accidently change anything in this object.

TY very much for replies :D
Change
1
2
3
4
5
6
7
8
// Allows a client to see the numerator's value.
	int get_numerator() {
		return numerator;
	}
	// Allows a client to see the denominator's value.
	int get_denominator() {
		return denominator;
	}

to
1
2
3
4
5
6
7
8
	// Allows a client to see the numerator's value.
	int get_numerator() const{
		return numerator;
	}
	// Allows a client to see the denominator's value.
	int get_denominator() const{
		return denominator;
	}


You should make your functions const when they do not change the state of the object the function is being invoked on. You expect your object unchanged when making it const, and so a call to a non-const member function wouldn't make sense.
Thank you big time man, really helped me :)
Topic archived. No new replies allowed.