1

I am implementing a class for rational numbers. I've created a constructor with parameters and all of my methods. I tried to add a default constructor as well, in the case that no parameters were provided.

These are the relevant sections of the code:

Rational::Rational(int numer, int denom){ //Constructor
    numer = numer;
    denom = denom;
}
Rational::Rational(){
  int numer = 1;
  int denom = 2;
}
#ifndef RATIONAL_H
#define RATIONAL_H

class Rational{
private:
    int numer;
    int denom;

public:
    Rational(int numer=1, int denom=2); // Tried to use this to provide defaults, but still generated errors unless I provided parameters in the Test Driver.
    Rational(); // Tried to make a separate default constructor, also causing errors
    int getNumer();
    int getDenom();
    Rational add(Rational b);
    Rational sub(Rational b); 
    Rational mult(Rational b); 
    Rational divide(Rational b); 
    void setValues(int numer, int denom);
    void print();
    void printFloat();
};


#endif

int main(){
    Rational r(3,4); // Succesfully creates a fraction 3/4
    Rational r1; //causes error

This is the error that trying to create the second, default, constructor generated, and I'm not quite sure what the problem is:

error: call of overloaded ‘Rational()’ is ambiguous

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Brenden Price
  • 517
  • 2
  • 9

1 Answers1

3

The default arguments in the first constructor already handle the case where no values are given. You shouldn't also create a default constructor. Delete it and your code will compile.

Rational::Rational(int numer, int denom){
    numer = numer;
    denom = denom;
}
Rational::Rational(){
  int numer = 1;
  int denom = 2;
}
class Rational{
    Rational(int numer=1, int denom=2);
    Rational();
};

Also you should use initializer lists to initialize variables in constructors rather than assignment statements:

Rational::Rational(int numer, int denom)
    : numer(numer), denom(denom)
{
}

For details see:

John Kugelman
  • 349,597
  • 67
  • 533
  • 578