Simplifying constructors

Oct 26, 2014 at 11:53pm
Hello everyone,

In an internet class I am following, we had to make a "fraction" class, that is, a class to handle rational numbers. To do this, I created the three following constructors:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Rational::Rational(): m_numerateur(0), m_denominateur(1)
{
}

Rational::Rational(int numerateur): m_numerateur(numerateur), m_denominateur(1)
{
}

Rational::Rational(int numerateur, int denominateur): m_numerateur(numerateur), m_denominateur(denominateur)
{
    if(denominateur == 0) // We check that the denominator is different than 0.
    {
        std::cout << "Erreur: le dénominateur doit être un entier différent de 0!" << std::endl;
    }
    else
    {
        if(denominateur < 0)
        {
            m_denominateur = -m_denominateur;
            m_numerateur = -m_numerateur;
        }
        else
        {
            // The fraction is already either of the form a(x,y), x,y>0 or of the form a(x,y), x<0, y>0.
        }
    }
}


After the homework was completed, the teacher wrote that those three constructors could be simplified into one constructor.

How is this possible?

Thank you for your time,

Eric
Oct 27, 2014 at 12:10am
http://www.cplusplus.com/doc/tutorial/functions/ (Default values in parameters)
Oct 27, 2014 at 12:26am
Thanks a lot ne555, works well!!
Topic archived. No new replies allowed.