3

I want to create an array to store actual objects and not pointers to objects in C++?

Can somebody explain how do I do that? is it better to use vectors or just directly like:

Student s [10];

OR

Student s [10][];
2
  • Does the second one even compile? Commented Mar 20, 2012 at 13:17
  • no, the second one doesn't compile. There are very few places in C++ where [] is valid syntax. Commented Aug 2, 2012 at 16:48

3 Answers 3

4

Using:

Student s [10];

Creates an array of 10 Student instances.

I think that Student s [10][]; is invalid.

But with C++ I'd not use C type arrays, it's better to use classes like std::vector or C++0x std::array which may not be available with not up-to date standard libraries/compilers.

Example for the above with a std::vector

#include <vector>

...

std::vector<Student> students(10);

And with an std::array:

#include <array>

...

std::array<Student, 10> students;
Sign up to request clarification or add additional context in comments.

6 Comments

thanks man I wanted to accept ur full answer but it doesn't allow me to do so :((
One more Q: how can I define Vector size in header file? can't I? How to redefine it then in the cc file?
A std::vector has no fixed size, you can .push_back() elements into it (and remove them). You can retrieve the current size with .size().
thnx but I have a known size of this vector.. Is it better fixing its size in advance?
If you type the size of the vector in its constructor like in the example above (std::vector<Student> students(10);) it has this as its initial size. If you don't remove elements from or insert elements into the std::vector the size does not change and you can use your fixed size. But unfortunately you cannot fix the size of the vector to a certain amount, but this should not worry you.
|
2

Don't use arrays. Arrays are C not c++. Use std::vector instead, which is the C++ way to handle this.

2 Comments

Can u suggest me a way to use Vectors to store actuall objects? thanks
@shaklasah: vectors always store actual objects unless you specifically tell them otherwise.
1

I would suggest using std::vector if you want to make your array growable, otherwise just use Student students[10]; for 10 objects.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.