FAQ 22.04 Is it normal for constructors to have nothing inside their body?

Yes, this happens frequently.

The body of a constructor is the {...} part. A constructor should initialize its member objects in the initialization list, often leaving little or nothing to do inside the constructor's body. When the constructor body is empty, it can be left empty, perhaps ({ }), or decorated with a comment such as

 // Intentionally left blank. 

An example follows (Fract is a fraction class).

 #include <iostream> using namespace std; class Fract { public:   Fract(int numerator=0, int denominator=1) throw();   int numerator()   const throw();   int denominator() const throw();   friend Fract operator+ (const Fract& a, const Fract& b) throw();   friend Fract operator- (const Fract& a, const Fract& b) throw();   friend Fract operator* (const Fract& a, const Fract& b) throw();   friend Fract operator/ (const Fract& a, const Fract& b) throw();   friend ostream& operator<< (ostream& ostr, const Fract& a) throw(); protected:   int num_;  //numerator   int den_;  //denominator }; Fract::Fract(int numerator, int denominator) : num_(numerator) , den_(denominator) { } int Fract::numerator()   const throw() { return num_; } int Fract::denominator() const throw() { return den_; } ostream& operator<< (ostream& ostr, const Fract& a) throw() { return ostr << a.num_ << '/' << a.den_; } int main() {   Fract a;                cout << "a = " << a << endl;   Fract b = 5;            cout << "b = " << b << endl;   Fract c = Fract(22,7);  cout << "c = " << c << endl; } 

The output of this program follows.

 a = 0/1 b = 5/1 c = 22/7 

Notice that the initialization list resides in the constructor's definition and not its declaration (in this case, the declaration and the definition are separate).



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net