FAQ 20.09 Should one constructor call another constructor as a primitive?

No. Even though it is possible, it won't do what the programmer wants.

Dragons be here: if a constructor of class Fred calls another constructor of class Fred, the compiler actually initializes a temporary local object of class Fred. It does not use the call to initialize the this object.

Both constructors can be combined by using a default parameter or their common code can be shared in a private: init() member function, but one constructor should not directly call another constructor. Here is an example of an init() function.

 class Fred { public:   Fred(int x)   throw();   Fred(float y) throw();   Fred(char* z) throw();   // ... private:   void init(int x, float y, char* z) throw();   // ... }; inline Fred::Fred(int x)   throw() { init(x, 0.3, NULL); } inline Fred::Fred(float y) throw() { init(-1, y, "foo"); } inline Fred::Fred(char* z) throw() { init(-2, 5.2, z);   } void Fred::init(int x, float y, char* z) throw() {   // ... } 


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