Class Member as an Array

Is it possible to have an array as a class member? It is part of my Wumpus Hunt exercise.

I want to do the following:
1
2
3
4
5
6
7
8
9
10
class Room {
   blah blah;
};

int main() {

for (i = 0; i < 3; i++) {
   Room adjacent[i];
      blah blah;
}

My compiler is not letting me do that. It warns that the variable must be constant.

Thanks in advance.
you can store a pointer in your class eg

1
2
3
4
5
6
7
 Class A{
private:
        int* p;
public:
        A();
        ~A();
};


and initialise it in the classes constructor

1
2
3
4
A::A()
{
        p = new int[10];
}
Please note; doing what quirky has supplied you will also need to delete the memory allocated with new during the objects destructor.
@ Quirky,

I don't follow how I would use the pointer in the main() section.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Room {
public:
 Room() { array = new int[10]; }
 ~Room() { delete [] array; }
 int *array;
}

int main() {
 Room myRoom;

 myRoom.array[0] = 4;

 return 0;
}


This isn't a very nice way to do it though. I'd recommend you look at using a std::vector instead. This example also breaks good OO convention by not encapsulating access to the pointer.
You have not given us the exact code or error messages, leading everyone to respond on the wrong trail.

I think that are you are trying to do something that requires a const value, but your class is not const-correct, causing your compiler to complain about the lack of constness.

Can you post more exacting information?
Continued in the thread titled Wumpus Hunt 2.
Topic archived. No new replies allowed.