C++ Array of Objects
Go to solution
Solved by fizzlesticks,
They are not all the same, so would you recommend using struct instead? I would have to write every single (thing[number].otherthing = blabla;) though.
Structs and classes are pretty much the same thing, so that wouldn't change anything.
You could have multiple constructors, one that takes no arguments used to create the array and another that takes all the data and copy new objects into the array like:
class A{public: A(){} A(int i, float x) : name(i), num(x){} int name; float num;};int main(){ A as[10]; as[0] = A(1, 0.2f); as[1] = A(4, 0.0f); as[2] = A(6, 1.3f); return 0;}
Or use pointers
class A{public: A(int i, float x) : name(i), num(x){} int name; float num;};int main(){ A* as[10]; as[0] = new A(1, 0.2f); as[1] = new A(4, 0.0f); as[2] = new A(6, 1.3f); //... as[10] = new A(10,1.2f); cout << as[1]->name; for(int i=0;i<10;++i) { delete as[i]; } return 0;}
edit: A better way of doing the first method would be like this without the pointless default constructor.
class A{public: A(int i, float x) : name(i), num(x){} int name; float num;};int main(){ A as[10] { A(0, .1f), A(0, .1f), A(0, .1f), A(0, .1f), A(0, .1f), A(0, .1f), A(0, .1f), A(0, .1f), A(0, .1f), A(0, .1f)}; return 0;}

Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now