tags:

views:

122

answers:

3

Hi, I got a C++ struct:

   struct Student{

         Student(){

         }
   };

And the enum:

   enum studenttype_t { levelA = 0, levelB = 1, levelC = 2 };

Then somewhere else it is declared:

   vector<Student *> student;

Could it be used as follows:

   student[levelA] = new Student();

If so, what does the student[levelA] mean? is it 0 in this case? and what is the function of the last statement, i.e. student[levelA] = new Student();? thanks

+2  A: 

That's exactly what student[LevelA] means. A vector is like an array, but expandable. All that

enum studenttype_t { levelA = 0, levelB = 1, levelC = 2 };
vector<Student *> student(5); // need a size, else defaults to zero.
student[levelA] = new Student();

is doing is creating such a vector (of Student pointers) and creating the first one (index 0).

paxdiablo
@paxdiablo: got it , thanks a lot, woooooo, what a high score you have:)
luna
Except that with just those 3 lines it tries to access the first element of an empty vector. It is not creating index 0. It is only accessing index 0. Presumably there is code not shown in the original question that actually creates the element(s) of the vector itself.
TheUndeadFish
Good point, @Fish, I assumed there _was_ code there to properly populate but, just to be safe, I've changed my snippet to make it kosher.
paxdiablo
+1  A: 

levelA is the constant, 0. student is a vector, and student[levelA] is the zeroth element of that vector. The elements of the vector are of type Student*, i.e. pointers to Student objects.

student[levelA] = new Student();

instantiates student[0] with a new Student class.

Jonathan
@Jonathan: thanks a lot! :)
luna
@luna - You don't need to thank every answer to you question. The [approved behavior](http://meta.stackoverflow.com/questions/17878/stack-overflow-etiquette-for-thanking-users-who-answered-my-question/17886#17886) is to give an upvote at least, or to work out an answer to one of their questions if you're really thankful - These do the job, and it don't generate any noise. [irony]But thanks for being polite![/irony]
reemrevnivek
@reemrevnivek: I am alway used to being thankful to others, and I always tend to help others, otherwise I could not feel sound and safe XD
luna
+5  A: 

Yes, levelA is 0. C++ allows a silent conversion from enum value to int (unlike C#, which requires a explicit cast).

student[levelA] = new Student(); means allocate memory in the heap, create a Student object in that memory, and store the address of the new object into the first element of the student vector. However, there is not necessary an element 0 in the vector -- when it was created, it had length 0 -- so that is actually undefined behavior.

student.push_back(new Student()); says add the new object to the next (presently the first) element of the vector.

James Curran
@James, thank you soooo much
luna