classes stuck. can't move forward. Help!

HI. I am beginner in classes. how to work with dynamic memory in classes. I am not able to allocate dynamic array simply in public or private field. so instead allocated the dynamic array in a constructor. but how to access it later either int main() or some other methods of classes like get function to get number stored in that index. eg:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class vectorofint
{
  public:
  vectorofint();
  int set(int index);

private:

};  

vectorofint::vectorofint()

{
    int *array=new int[32];
}

int vectorofint::set(int index)
{
    array[index]=8;///says array is out of scope. how to access the array???
}
Try this delete int at line 14, and declare int*array as member of class
well, doing what u suggested, it didn't show any error. but now while using set function, it gives error: "expected unqualified id before '.' token".

what i did

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

class vectorofint
{
  public:
  vectorofint();
  int get(int index);
  void set(int index);





  private:
  int *array;



};


void vectorofint::set(int index)
{
    array[index]=8;
}

vectorofint::vectorofint()

{
    int *array=new int[32];
    

}

int main()
{
    class a;
        a.set(8);///gives error at this line

}


Last edited on
Line 36 use vectorofint a; not class a;
well, again solved the problem but again "program not responding". is there any memory leak?
Line 29 you havent delete int*
is it necessary to delete it? just a little bit of memory dynamically allocated. don't see why it should run out of memory.
also even if i delete it using a destructor, still doesn't solve the problem. destructor used:

1
2
3
4
vectorofint::~vectorofint()
{
    delete array;
}


still same "program not responding".
I mean remove int* from line 29 because *array is already declared
You should have seen me smile right now. it worked! thnx a loooooot.
Topic archived. No new replies allowed.