CODE
#include <iostream>
using namespace std;
class Fraction {
private :
int numerator;
int denominator;
public :
Fraction() {
}
Fraction(int numerator, int denominator) {
this -> numerator = numerator;
this -> denominator = denominator;
}
int getNumerator() const {
return numerator;
}
int getDenominator() const {
return denominator;
}
void setNumerator(int n) {
numerator = n;
}
void setDenominator(int d) {
denominator = d;
}
void print() const {
cout << this -> numerator << " / "
<< denominator << endl;
}
void simplify() {
int gcd = 1;
int j = min(this -> numerator, this -> denominator);
for(int i = 1; i <= j; i++) {
if(this -> numerator % i == 0 &&
this -> denominator % i == 0)
{
gcd = i;
}
}
this -> numerator = this -> numerator / gcd;
this -> denominator = this -> denominator / gcd;
}
void add(Fraction const &f2) {
int lcm = denominator * f2.denominator;
int x = lcm / denominator;
int y = lcm / f2.denominator;
int num = x * numerator + (y * f2.numerator);
numerator = num;
denominator = lcm;
simplify();
}
void multiply(Fraction const &f2) {
numerator = numerator * f2.numerator;
denominator = denominator * f2.denominator;
simplify();
}
};
int main() {
Fraction f1(10, 2);
Fraction f2(15, 4);
Fraction const f3;
cout << f3.getNumerator() << " "
<< f3.getDenominator() << endl;
f3.setNumerator(10);
}
KEY-NOTES
- We cannot change any property(data member) of the class when an object is a constant object because changes are not allowed in a constant object.
- Fraction const f3;
- Only constant functions can be called from constant objects. Normal functions cannot be called from constant functions
- Constant functions are those which doesn't change any property of the object.
- void print() const {cout << this -> numerator << " / "<< denominator << endl;
- A constant function cannot change an object's properties.
- We can call constant functions/data members from normal objects.
- We should always mark a function as a constant function when it does not change the properties of an object.
0 Response to "Constant Functions and Constant Objects | OOPS"
Post a Comment
If you have any doubts, please let me know...