I have a program, call it X, that uses two classes: call them Y and Z. X uses Y which uses Z. Y contains an array of Z's.
How do I construct an array of Z's and still allow me to set Z's variables.
For example I know how to declare an array of classes:

Z arrayOfZ[NUM]

and I know how to set values:

Z newZ(5)

but how do I do both?

Thanks

Not sure if I udnerstand the question, but I think you mean something along the lines of setting a value of one of the Z variables in the array?

struct Z{

    int a;
    int b;

    Z() : a(0), b(0) {}

    void setA(int x){ a = x; };
    void setB(int y){ b = y; };
};

int main(){

   Z arrayOfZ[10];
   Z[0].setA(5);
   
   // ... etc
   

   return 0;
}

If not and you want to construct an array of Z's with a specified constructor to apply for each Z, I don't know but I think its possible.

#include<iostream>
using std::cout;

struct Test
{
	int i;
	Test(int j) { i = j; }
	void show() { cout << i << "\n"; }
};
int main() 
{
	Test test[3] = { Test(1), Test(2), Test(3) };
	test[0].show();
	test[1].show();
	test[2].show();
  return 0;
}

//prints 1 2 3

Of course you know that struct and classes are almost similar except
for their default behavior, so you can do this with classes as well.

Test test[3] = { Test(1), Test(2), Test(3) };

That's exactly what I was looking for! Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.