In class three, we continue our discussion of C++ by extending
our Rational class.  We investigate constructors and begin to look
at operator overloading.


CONSTRUCTOR BASICS Question -- when we declare a variable Rational x; how does the compiler know how to construct it?? Answer -- The compiler provides a default constructor for both built-in types and classes (user defined types) If you do nothing, this default constructor will be called. Sometimes that's OK, but usually you want to write your own constructor. If you write any constructor, you do not get the default constructor. A constructor is member function with the same name as the class. It has no parameters and no return type --- not even VOID
Rational class definition with constructors. Another version of rational.h #ifndef __RATIONAL_H_ #define __RATIONAL_H_ class Rational { private: int num; int den; public: // default constructor Rational(); // construct a Rational from one int (the numerator) Rational (const int n); // construct a Rational from two ints Rational (const int n, const int d); // destroy a Rational ~Rational() { } // nothing special to do // accessors int Num() const; int Den() const; void Num (const int n); void Den (const int d) { den = d; } };
// Rational class constructors // the implementation -- in .C or .h // the default constructor Rational::Rational() { // what should the default behavior be? } // construct a Rational from just the numerator // uses assignment within the body of the function Rational::Rational (const int n) { num = n; den = 1; } // construct a Rational from both numerator // and denominator, using the initialization list Rational::Rational (const int n, const int d) : num(n), den(d) { // no code??? } EXAMPLE usage Rational x; // calls Rational(); Rational y(-5); // calls Rational (int) Rational z(3,4); // calls Rational (int, int) NOTES on initialization list 1. The initialization list is required if you are trying to initialize a component object. 2. The initialization list is faster because fewer function calls are made 3. The data members of the object are initialized in the order they are defined, regardless of the order they appear in the initialization list.