Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint

2.12. Conversions

A constructor that can be called with a single argument (of a different type) is a conversion constructor because it defines a conversion from the argument type to the constructor’s class type.

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;
}

					  


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial