FAQ 22.12 How can an array of objects be initialized with specific initializers?

Why use arrays in the first place? Why not use containers, particularly from the standard library? If arrays are a must, and if the elements require specific initializers, the answer is the {...} initializer syntax.

 #include <iostream> using namespace std; class Stack { public:   Stack(int maxLen=5) throw();   Stack(const Stack& s) throw();   // ... }; Stack::Stack(int maxLen) throw() { cout << "Stack: maxLen=" << maxLen << '\n'; } Stack::Stack(const Stack& s) throw() { cout << "Stack: copy ctor\n"; } int main() {   // 'a' will be constructed with maxLen=7:   Stack a(7);   // All 4 stacks in 'b' will be constructed with maxLen=5   Stack b[4];   // c[0] will copy from a, c[1] maxLen=8, c[2] maxLen=7,   // c[3] will be constructed without arguments (maxLen=5):   Stack c[4] = { a, Stack(8), 7 }; } 

The (annotated) output of this program follows.

 Stack: maxLen=7                                      <-- 1 Stack: maxLen=5                                      <-- 2 Stack: maxLen=5                                      <-- 3 Stack: maxLen=5                                      <-- 4 Stack: maxLen=5                                      <-- 5 Stack: copy ctor                                     <-- 6 Stack: maxLen=8                                      <-- 7 Stack: maxLen=7                                      <-- 8 Stack: maxLen=5                                      <-- 9 

(1) This is a

(2) This is b[0]

(3) This is b[1]

(4) This is b[2]

(5) This is b[3]

(6) This is c[0]

(7) This is c[1]

(8) This is c[2]

(9) This is c[3]



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