2.12.  Conversions

[ fromfile: conversions.xml id: conversions ]

Example 2.19. src/ctor/conversion/fraction.cpp

class Fraction {
public:
    Fraction(int n)                  1
       : m_Numer(n), m_Denom(1) {}
    Fraction(int n, int d )
       : m_Numer(n), m_Denom(d) {}
    Fraction times(const Fraction& other) {
       return Fraction(m_Numer * other.m_Numer, m_Denom * other.m_Denom);
    }
private:
    int m_Numer, m_Denom;
};
int main() {
    int i;
    Fraction frac(8);                2
    Fraction frac2 = 5;              3
    frac = 9;                        4
    frac = (Fraction) 7;             5
    frac = Fraction(6);              6
    frac = static_cast<Fraction>(6); 7
    frac = frac2.times(19);          8
    return 0;
}

1

Single argument ctor defines a conversion from int.

2

Conversion constructor call.

3

Copy init (calls conversion ctor too).

4

Conversion followed by assignment.

5

C-style typecast (deprecated).

6

Explicit temporary, also a C++ typecast.

7

Preferred ANSI style typecast.

8

Implicit call to the conversion constructor.


Example 2.20. src/ctor/conversion/fraction.h

class Fraction {
public:
    Fraction(int n, int d = 1)
            : m_Numer(n), m_Denom(d) {}
    Fraction times(const Fraction& other) {
       return Fraction(m_Numer* other.m_Numer, m_Denom* other.m_Denom);
    }
            
private:
    int m_Numer, m_Denom;
};




[19] Section 19.8.4 informally discusses an example.