# Returning object from function

Printable View

• 03-14-2011
843
Returning object from function
I'm trying to return an object from the function toFraction, which takes a decimal number as input and returns an object with the converted fraction class. The problem I'm having is storing the object, and then displaying it. Any help is appreciated.

Code:

```class Fraction {     int top, bottom; public:     Fraction(int a = 0, int b = 1);     ~Fraction(){} Fraction::Fraction (int a, int b) {     if (b < 0){         a = -a; b = -b;}     top = a; bottom = b; } Fraction Fraction::toFraction(double x) {     int n;     double u,v;     for (n = 1; u < 1; n++){     u = x*10*n; cout << u;     v = 10*n;}     Fraction temp(u,v);     return temp; } int main(void) {     Fraction a(5,-8);     Fraction b(1,0);     Fraction c;     double dec = 0.00345;     cout << "Decimal value = " << dec <<endl;     c.toFraction(dec);     cout << "Converted to fraction = ";     c.display();     return 0; }```
• 03-14-2011
kmdv
Code:

```class Fraction {     int top, bottom; public:     Fraction(int a = 0, int b = 1);     ~Fraction(){} Fraction::Fraction (int a, int b) {     if (b < 0){         a = -a; b = -b;}     top = a; bottom = b; } Fraction Fraction::toFraction(double x) const {     int n;     double u,v;     for (n = 1; u < 1; n++){     u = x*10*n; cout << u;     v = 10*n;}     return Fraction(u,v); } int main(void) {     Fraction a(5,-8);     Fraction b(1,0);     Fraction c;     double dec = 0.00345;     cout << "Decimal value = " << dec <<endl;     cout << "Converted to fraction = ";     c.toFraction(dec).display();     return 0; }```
Maybe this way.
• 03-14-2011
843
Thank you! The multiple dots must have confused me. What does the const do in this case? To prevent the object from changing?

By the way, why is the resulting fraction automatically simplified? I have yet to implement this. EDIT: Ah, it's rounded off.
• 03-14-2011
kmdv
'const' in this case informs the compiler that the method will not alter object state, thus it can be used on an instance marked as const.