assert statement is not working

Practicing template class. This is a generic array class, but I'm not sure why the program does not terminate when I try to call "list[100] = 's'; ". Thanks in advance, making a lot of progress in C++.

(VS code, windows)

The header file:
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#ifndef arrayType_H
#define arrayType_H

#include <iostream>
#include <cassert>


template <class elemType>
class myArray
{
 
    public:

    elemType & operator [] (int x); 
    void operator = (const myArray &); 

    myArray(const myArray &);
    myArray(int a = 0, int b = 0);

    ~myArray();

    elemType * array;

    private:   

     
    int endPoint;
    int length; 

};

template <class elemType>
elemType & myArray<elemType>::operator [] (int x)
{

    assert(x >= endPoint && x <= endPoint + length);
    return array[x-endPoint]; 
} 


template <class elemType>
void myArray<elemType>::operator = (const myArray & otherArray)
{
    delete array; 
    length = otherArray.length;
    endPoint = otherArray.endPoint;
    decltype(otherArray[0]) * array;
    array = new decltype(otherArray[0]) [length];
    for(int k = 0; k < length ; k++)
    {
        array[k] = otherArray[k];
    }
}

template <class elemType>
myArray<elemType>::myArray(const myArray & otherArray)
{
    length = otherArray.length;
    endPoint = otherArray.endPoint;
    array = new decltype(otherArray[0]) [length];
    for(int k = 0; k < length ; k++)
    {
        array[k] = otherArray[k];
    }
}


template <class elemType>
myArray<elemType>::~myArray()
{
    delete array; 
}


template <class elemType>
myArray<elemType>::myArray(int a, int b)
{
    assert(a<= b); 
    array = new elemType[b-a]; 
    endPoint = a; 
}javascript:PostPreview()

#endif  


The test program is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include "arrayType.h"

int main ()
{
    myArray<char>list(1,5);
    list[1] ='a';
    list[2] = 'p';
    list[3] = 'p';
    list[4] = 'l';
    list[5] = 'e'; 
    std::cout << list[3]; 
    myArray<int>testL(3,5);
    list[100] = 's'; 
    std::cout << list[100]; 
}
Amongst other things (I haven't actually tried your code):
- you don't set length in your constructor, so it is unusable
- you don't allocate enough memory for your array; line 79 should have b-a+1, not b-a (e.g. 5-1 is 4, not 5]
- I presume you need a [] in line 71
Last edited on
@lastchance

Thanks for pointing out my mistakes, I think it is all sorted now.
Now it outputs "pAssertion failed: x >= endPoint && x <= endPoint + length, file arrayType.h, line 47" which I believe is the correct message I should be getting.

Thanks again, have been helped quite a few times by people in this forum.
Topic archived. No new replies allowed.