<***@eyou.com> wrote in message news:***@f14g2000cwb.googlegroups.com...
| class A
| {
| public:
| A();
| virtual ~A(){}
| ...
|
| private:
| int m_iarray[10];
| }
|
| How can I initialize "m_iarray" int the member initialization list? If
| cann't, then why?
|
To initialize the array to any specific value, you have to wrap its
element type and provide your own default ctor.
Why? Because arrays are primitive containers that adhere to a couple of
old rules:
a) they must be initialized to a known constant size
b) each element of the array must have a default ctor available and
invokeable at birth.
Suppose that we replaced the int type above with a simple struct N. You
would not be able to generate an instance of class A if type N did not
have a default ctor available. Try it, comment the default ctor below...
// test_array.cpp
#include <iostream>
struct N
{
int m_n;
N() : m_n(0) { std::cout << "N() "; } // def ctor
N(int n) : m_n(n) { std::cout << "N(int n) "; }
~N() { std::cout << "~N() "; }
};
class A
{
N m_array[10];
public:
A() { std::cout << "A()\n"; }
~A() { std::cout << "\n~A() "; }
};
int main()
{
A a;
return 0;
}
/*
N() N() N() N() N() N() N() N() N() N() A()
~A() ~N() ~N() ~N() ~N() ~N() ~N() ~N() ~N() ~N() ~N()
*/
______
If this limitation of the array is an issue, consider the std::vector. A
much more flexible, dynamic and capable container, not to mention much,
much easier to use.
______
// test_vector.cpp
#include <iostream>
#include <vector>
#include <algorithm>
template < class T >
class V
{
std::vector< T > m_v;
public:
V(int size, T value) : m_v(size, value) { }
~V() { }
void display() const
{
std::cout << std::endl;
std::copy( m_v.begin(),
m_v.end(),
std::ostream_iterator< T >(std::cout, " ") );
}
};
int main()
{
// generate an instance of usertype V with
// a vector of 10 int elements all initialized to 1
V<int> v(10, 1);
v.display();
// a vector of 10 doubles initialized to 9.9
V<double> vd(10, 9.9);
vd.display();
return 0;
}
/*
1 1 1 1 1 1 1 1 1 1
9.9 9.9 9.9 9.9 9.9 9.9 9.9 9.9 9.9 9.9
*/