0

I'm trying to make Fraction object and overload a few operators. The problem is at the moment I want to multiply two fractions, because it returns fraction with numerator equals to -858993460 as well as denominator.

Fraction::Fraction(int numerator, int denominator)
{
    if (denominator == 0)
        throw std::overflow_error("Denominator can't be 0");
    else {
        this->numerator = numerator;
        this->denominator = denominator;

        if (this->numerator < 0 && this->denominator < 0) {
            this->numerator = -this->numerator;
            this->denominator = -this->denominator;
        }
    }
}

Fraction::Fraction(const Fraction & scndFraction)
{
    if (scndFraction.denominator == 0)
        throw std::overflow_error("Denominator can't be 0");
    else {
        this->numerator = scndFraction.numerator;
        this->denominator = scndFraction.denominator;
    }
}

Fraction & Fraction::operator*(const Fraction& scndFraction)
{
    // TODO: Sem vložte návratový příkaz.
    Fraction newFraction(this->numerator*scndFraction.getNumerator(),
        this->denominator*scndFraction.getDenominator());

    return newFraction;
}

And main.cpp

#include "Fraction.h"
#include <Windows.h>

int main() {
    //HANDLE hnd = GetStdHandle(STD_OUTPUT_HANDLE);
    //SetConsoleTextAttribute(hnd, FOREGROUND_BLUE);

    Fraction first(1, 2);
    std::cout << first.getFraction() << std::endl;

    Fraction second(1, 2);
    std::cout << second.getFraction() << std::endl;

    Fraction third = second * first;
    std::cout << third.getFraction() << std::endl;

    getchar();

    return 0;
}
HonzsSedlomn
  • 236
  • 3
  • 14
  • 2
    Change the return type of `Fraction::operator*` from `Fraction &` to `Fraction`. – songyuanyao Apr 29 '17 at 12:42
  • Oh god. It works. And why is it as it is? – HonzsSedlomn Apr 29 '17 at 12:43
  • 1
    [undefined behaviour](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope). Turn on your compiler warnings. – chris Apr 29 '17 at 12:44
  • @HanísekSedloň You're returning a local variable by reference, the local variable will be destroyed when get out of the function, then the reference becomes dangled. Dereference on it will be UB. – songyuanyao Apr 29 '17 at 12:48
  • 1
    'this->' prefix to data attributes of the instance are not needed. instance's of same class have 'friend' like access to each other ... " this->numerator * scndFraction.getNumerator() " can be written as " numerator * scndFraction.numerator " – 2785528 Apr 29 '17 at 12:51
  • 1
    "warning: reference to local variable ‘retVal’ returned [-Wreturn-local-addr]" add bracket contents to your compile command – 2785528 Apr 29 '17 at 12:55

0 Answers0