FAQ 22.01 What are constructor initialization lists?

Constructor initialization lists are the best way to initialize member objects.

All member objects are initialized before the body of the constructor begins executing. Constructor initialization lists allow the class to exercise control over the construction of the member objects before the execution of the constructor.

Here is an example of using an initialization list.

 #include <new> #include <string> using namespace std; class Person { public:   Person(const string& name) throw(bad_alloc);   // ... protected:   string name_; }; Person::Person(const string& name) throw(bad_alloc) : name_(name)                                        <-- 1 {                                                      <-- 2 } int main() {   Person fred("Fred Flintstone");   // ... } 

(1) The initialization list copies name into name_

(2) Note: No assignment here since the init list copies name into name_



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