Class declaration of "More Effective C++", Item 30

After reading the item of the book, I am trying to implement it. However, there are only four lines of code in the book (lines with comment // book). I added other members. Is the following code a correct class declaration for the item?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
template<typename T>
class Array2D
{
public:
	explicit Array2D(unsigned in_2DNumElm, unsigned in_1DNumElm);
	~Array2D();

	class Array1D		
	{
	public:
		explicit Array1D(unsigned in_1DnumElem);
		~Array1D();

		T& operator[](unsigned index);				// book
		T const& operator[](unsigned index) const;	// book
		
	private:
		unsigned m_1Dsize;
		T* m_1Darray; 
	};

	Array1D operator[](unsigned index);				// book
	Array1D const operator[](unsigned index) const;	// book
private:
	unsigned m_2Dsize;
	Array1D* m_2Darray;
};


It seems I should declare:
 
Array1D** m_2Darray;


With Array1D** m_2Darray;I got compilation error of 'Array2D<T>::Array1D' : no appropriate default constructor available:
1
2
3
4
5
6
7
template<typename T>
Array2D<T>::Array2D(unsigned in_2DNumElm, unsigned in_1DNumElm) : m_2Dsize(in_2DNumElm)
{
	m_2Darray = new Array1D[m_2Dsize];
	for (unsigned i = 0; i < m_2Dsize; ++i)
		m_2Darray[i] = Array1D[in_1DNumElm];
}
Last edited on
Arrays with the new operator require that the type/class of the elements in the array has default constructor. Array1D has a non-default (Array1D(unsigned in_1DnumElem)) constructor and mere presence of user-defined constructor suppresses the compiler generated implicit one. The result is that you need to implement default constructor with the prototype Array1D() or to provide default value for the in_1DnumElem argument in the existing constructor.

Regards
Alternatives to the default constructor:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 //Array1D** m_2Darray;
m_2Darray = new Array1D *[m_2Dsize];
for (unsigned i = 0; i < m_2Dsize; ++i)
	m_2Darray[i] = new Array1D(in_1DNumElm);

//std::vector<Array1D> m_2Darray
m_2Darray.reserve(m_2Dsize); 
for (unsigned i = 0; i < m_2Dsize; ++i)
	m_2Darray.push_back( Array1D(in_1DNumElm) );

//Array1D *m_2Darray;
 //emulating std::vector
std::allocator<Array1D> A;
m_2Darray = A.allocate( m_2Dsize );
for (unsigned i = 0; i < m_2Dsize; ++i)
	A.construct( m_2Darray+i, Array1D(in_1DNumElm) );
Last edited on
Topic archived. No new replies allowed.