0

What is the proper way to implement this class function when using pointers. I understand the basics of pointers, but it gets confusing. I'm trying to create a function that adds fractions.

f3 =  f1->add(f2);

Everything else in the class is running correctly.

#include <iostream>
using namespace std;

//members of a class default to private
class Fraction
{
private:
    int numerator;
    int denominator;

public:
    Fraction();
    Fraction(int,int);
    ~Fraction();
    Fraction* add(Fraction &f);
    void setFraction(int, int);
    int getNumerator();
    int getDenominator();
    };
Fraction::Fraction()
{
    numerator = 0;
    denominator = 0;
}
Fraction::Fraction(int num, int den)
{
    this->numerator = num;
    this ->denominator = den;
}
Fraction::~Fraction()
{
}
void Fraction::setFraction(int num, int den)
{
    numerator = num;
    denominator = den;
}
int Fraction::getNumerator()
{
    return numerator;
}
int Fraction::getDenominator()
{
    return denominator;
}
Fraction* Fraction::add(Fraction &f)
{
    int num = f.numerator * this->denominator;
    num += this->numerator *f.denominator;
    int den = this->denominator * f.denominator;
    return new Fraction(num,den);
}

int main() {
    Fraction* f1 = new Fraction(5,8);
    Fraction* f2 = new Fraction(1,8);
    cout << f1->getNumerator() << "/" << f1->getDenominator() <<endl;
    Fraction* f3 = new Fraction();
    f3 =  f1->add(f2);
    return 0;
}
8
  • 5
    Did you by chance start learning programming in Java? Commented Sep 30, 2016 at 14:14
  • 2
    The parameter is a reference, not a pointer. And you should not be returning pointers to newed objects, but objects by value. Commented Sep 30, 2016 at 14:14
  • 2
    Your function signature takes a reference (Fraction &f) but you're passing a pointer by using new so you can change to do f3 = f1->add(Fraction(1,8)) Commented Sep 30, 2016 at 14:15
  • 1
    @TimBotelho if you include that error in your question, it will help others to answer. Commented Sep 30, 2016 at 14:24
  • 4
    You really don't want to be using pointers here, let alone dynamic allocation. Commented Sep 30, 2016 at 14:27

1 Answer 1

2

If you want to pass in a pointer into a function (doesn't matter if it's a member or not), make the function signature that way:

Fraction* Fraction::add(Fraction* f)
                                ^ pass a pointer in
Sign up to request clarification or add additional context in comments.

1 Comment

OP doesn't really want to do this!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.