Class templates - strange constructor behavior

Hey,
I am currently studying the use of class templates in C++. I created the class

1
2
3
4
5
6
7
8
9
10
11
12
13
template<class elemType>			
class listType						// class template
{
	public:
		void insertAt(const elemType& item, int position);
		void print() const;
		listType(int listSize = 50);
		~listType();
	protected:
		elemType *list;
		int length;
		int maxSize;
};


with this constructor

1
2
3
4
5
6
7
8
9
template <class elemType>
listType<elemType>::listType(int listSize)  // constructor
{
	maxSize = listSize;
	length = 0;
	list = new elemType[maxSize];
	for(int i = 0; i < maxSize; i++)
		list[i] = 0;
}


and this print function

1
2
3
4
5
6
7
8
template <class elemType>
void listType<elemType>::print() const		// print
{
	int i;
	for (i = 0; i < length; ++i)
		cout << list[i] << " ";
	cout << endl;
}


Now, in my main() I want to test this out, so my code is:

1
2
3
4
5
6
7
8
9
int main()
{
	// using the class template
	listType<int> intList(10); 	// int implementation of class
		
	intList.print();
	for (int k = 0; k < 10; k++)
		intList.insertAt(1, k);
	intList.print();


The output should print the intList initialized with 0 as specified in the constructor, yet it doesn't print anything. After "reinitialization" in the for loop in the main function prints the 10 numbers (here: ones) with no problems.

Now it seems the constructor's initialization is working, at least "a bit". If I put k in the for loop to, let's say 3 (so elements 3 to 10 of the array are initialized with 1 using the insertAt function) it prints the first 3 zeros from the initialization in the constructor and then 4 more 1, for a total of 7 elements printed. It should though print 3 zeros and 7 ones for a total of 10 numbers. I am not sure what's going on here, maybe someone can explain me what is happening here? :)

Thanks a lot!
Razr
The output should print the intList initialized with 0 as specified in the constructor, yet it doesn't print anything.


Ahem:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
template <class elemType>
listType<elemType>::listType(int listSize)  // constructor
{
	maxSize = listSize;
	length = 0;   //<-  !!!!!!!!!!!!!!!!!!!!!
	list = new elemType[maxSize];
	for(int i = 0; i < maxSize; i++)
		list[i] = 0;
}
//...

template <class elemType>
void listType<elemType>::print() const		// print
{
	int i;
	for (i = 0; i < length /* <- !!!!!!!!!!!! */; ++i)
...of course...
I feel like I should apologize for wasting everybody's time... ;-)
Thanks a lot!
No problem.

And don't feel like that. Sometimes a fresh set of eyes is necessary to see a problem.
Topic archived. No new replies allowed.