Class with an array from another class

Im trying to make a class with an array from another class.
Obj
1
2
3
4
5
6
class Obj {
int i;
public:
Obj ();// default constructor; 
Obj (int j) {i=j;};
};

Array
1
2
3
4
5
6
7
 class Arr {
Obj* P;  //??
int length;
public:
Arr (int i) {
length=i; 
P=new Obj[length];};


With ?? is the main problem because i have tried different combinations with Obj** P etc, but it only creates one instance of the class Obj.
The only thing that created multiple instances was Obj* P[10] but I can't use constant because i don't know in advance how much Obj I need. Also I am not alowed to use vectors. Please help because I'm stuck on this for 36 now.

With ?? is the main problem
Why's the problem? You're right that's the way dynamic arrays are declared. Use delete[] to destroy (in your destructor)
(don't just try random combinations) If the array cannot change its size you could try this
1
2
3
4
5
6
7
template <int n>
class Arr{
private:
  Obj P[n];
};
//...
Arr<10> array;
Sorry it's not dynamic.
Last edited on
The problem is that he creates array of Obj but with only one member. If I try to input 3, 2, 1 in a loop, he will just create one Obj with value 3 and the rest he will ignore. There is nothing wrong with the loop because I see in the debugger that he initalize P with space for only one Obj, and I want to have pointer array of n Obj.

I can't initialize it with P[n] because n must be a constant and i dond now what that number will be at the begining.

The only time it has correctly created array is with Obj* P[10] where he created array P with space for 10 Obj.

Edit: I you didn't understand me he will create array P but that array will just be P[0].
Last edited on
The creation is fine. Post when you use it.
In main i will do

1
2
3
4
5
6
 int main() {
int i=13;  // i is the length that i will calculate before calling Arr
Arr PO(i);
PO.work();
PO.read();
}


where work and read will be defined as
1
2
3
4
5
6
7
8
9
 void Arr::work {
for (int i=0; i<length; i++) {
int j;
cin >> j;
P[i]= Obj(j) 

void Arr::read () {
for (int i=0; i<length; i++) 
cout << P[i].give(); // where give is a method from Obj with { return i; } 


There is something wrong with the creation because he will just make P[0].
I'm sorry i have misunderstud debuger and the pointer this.
What I wrote is the correct way to create an array.

Thank you for your time.
Topic archived. No new replies allowed.