#include <iostream>
#include <cstdlib>
usingnamespace 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.
// 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.