Classes / constructor problem

Hi, I am trying to learn the classes and constructor. And I have a problem in this code.

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
#include <iostream>

using namespace std;

class vectorofint
{
public:
    vectorofint();
    vectorofint(int number);
   int getvalue(int number);
   void setvalue(int index,int number);
private :
int value[];
};

vectorofint::vectorofint()
{
    value[32];

    for(int i=0;i<32;i++)
    {
        value[i]=0;
    }
}

vectorofint::vectorofint(int number)
{
    value[number];
    for(int i=0;i<number;i++)
    {
        value[i]=0;
    }
}

int vectorofint::getvalue(int number)
{
    return value[number];
}

void vectorofint::setvalue(int index,int number)
{
    value[index] = number;
}


int main()
{
   vectorofint vector1(8);
   vector1.setvalue(7,5);
cout << vector1.getvalue(7);
   return 0;
}


The problem is that when I run this program it crash and windows give me an error message. Can anyone tell me what is wrong in my code? Thanks
vector1.setvalue(7,5); should be vector1.setvalue(7.5);
That is not his problem fafner look at line 40.

Maybe your problem is line 18 not sure why its there or what its doing. Also I think you would be better off using a pointer instead of [] but thats just me. I haven't used [] array in a class so not sure if thats even how you declare it.
giblit is on the right track.

@ line 18, you are not creating an array of size 32, you are attempting to set the value of the array @ element 32.

One way to fix this:
Remove line 18 completely. Change line 13 from
int value[];
to
int value[32];

Any time you get a segfault error when compiling and you've been playing with arrays, chances are you tried to read/write outside of the array. A classic example is messing up a for loop by going 1 too many iterations.
Last edited on
Ok thanks. Indeed for my needs im best to go with pointers (linked list).
Woops, embarassing, haha :P Sorry, my bad!
@Rekarth


As you want that the array defined in your class would have variable length you should substitute it for pointer and allocate memory for the array dinamically using operator new[].
Topic archived. No new replies allowed.