0

I'm quite new to C++ and I was wondering if there is any way around duplicating constructors, with variations in the passed arguments. I need to identify the correct given value (either float or int), check if the float can nicely be casted to an integer (e.g. 1.0) and call another constructor that accepts two integers if my values pass the test.

If anyone as any tips on improving this solution in general that would be great.

Fraction(int n, int d) : numerator(n), denominator(d) {
    simplify(n, d);
}

Fraction(float n, float d) {
    if (!isInteger(n) && !isInteger(d)) {
        throw invalid_argument("Fractions only accept real numbers.");
    } else {
        Fraction(int(n), int(d));
    }
}

Fraction(int n, float d) {
    if (!isInteger(n) && !isInteger(d)) {
        throw invalid_argument("Fractions only accept real numbers.");
    } else {
        Fraction(int(n), int(d));
    }
}

Fraction(float n, int d) {
    if (!isInteger(n) && !isInteger(d)) {
        throw invalid_argument("Fractions only accept real numbers.");
    } else {
        Fraction(int(n), int(d));
    }
}
8
  • Delegated constructors if your compiler supports them. Commented Oct 27, 2014 at 22:22
  • 4
    If you only want to support integer values, why do you want an option that takes float? Commented Oct 27, 2014 at 22:22
  • 1
    Your logic is wrong for the conditionals. Also, why are you checking that the arguments are integers? The compiler should do this already. Adding useless messages, and throwing exceptions just makes your code longer. Commented Oct 27, 2014 at 22:26
  • 1
    Because I want to be able to check if the passed parameter is a decimal. If I initialise my class with Fraction(9, 3.1), my values will be casted to int and thus become 9 and 3 but I want to be able to retrieve the original value of 3.1. Commented Oct 27, 2014 at 22:35
  • To clarify: you want to allow , at runtime, a float to be passed which does hold an exact integer value? Commented Oct 27, 2014 at 22:46

1 Answer 1

1

Well you could use only the floats ctor and test your parameters.
If you only have two ctors one for ints and one for floats, then only if both numbers are int the ints ctor will be called. otherwise the floats ctor will be called.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I guess I'm just going to stick with the first constructor, without doing any checks on the data type.
You can also use only the floats ctor and always check your parameters. Whatever suits you best :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.