Computer Science Canada

How does array of objects work in C++?

Author:  HazySmoke)345 [ Sat Nov 29, 2008 10:58 pm ]
Post subject:  How does array of objects work in C++?

Say that I have a class that looks something like this

code:
class point{
    int x, y;
};


I'm wondering what does the following lines of code do:

code:
int main(){
    point p[100];
    point *q = new point[100];
    ...
}


For the first line, does the program automatically create new instances of the 'point' class for every element in the array?
For the second line, do I have to create new instances of the 'point' class by using the 'new' operator on every element?

Thanks for reading this through. I really appreciate it.

Author:  md [ Sun Nov 30, 2008 6:43 pm ]
Post subject:  RE:How does array of objects work in C++?

In the first case the compiler allocates an array of 'point's and calls point::point for each one (in this case not specified).

In the second the compiler would do the same, except it would allocate the memory on the heap at run time instead of on the stack at compile time.

It should be fairly easy to verify by writing a simple constructor that outputs 'this' (the structure's address).


: