views:

188

answers:

4

I had a quiz at school and there was this question that I wasn't sure if I answered correctly. I could not find the answer in the book so I just wanted to ask you.

Point* array[10];

How many instances of class Point are created when the above code is called?

I answered none because it only creates space for 10 instances, but doesn't create any. Then my friend said it was just one because when the compiler sees Point* it just creates one instance as a base.

+13  A: 

It creates no Points.

What it does is creates an array of ten pointers that can point to Point objects (it doesn't create space for ten instances). The pointers in the array are uninitialized, though, and no Point objects are actually created.

James McNellis
thanks.... i knew i was wrong about allocating the space. the question just asked how many, but my dumb ass had to give an explanation when i didn't need it.
+4  A: 

You are almost correct.

The code creates no instances of Point. It does create 10 instances of Point *, though. It does not create the space for the Point instances; that is done using a call to new, for example.

strager
+2  A: 

Point* array[10] creates an array with ten slots for pointers, numbered 0..9.

You are both wrong - no initialisation takes place in C++ with such a statement, unless

  1. you are running a special memory allocator which zeros memory, such as SmartHeap (or C++/CLI) or
  2. if the array is outside of a function (eg: just within a .cpp file as global), in which case all the pointers are zeroed.

Absolutely no instances are created.

Respectfully disagreeing with strager's point, there is no such thing as an instance of Point* and it would be dangerous to think of such a thing existing. There is only space for a pointer and compile-time checking to ensure you can only assign a pointer of that type, or pointer to a subclass, into that pointer.

Andy Dent
What about instances of `Point *`?
strager
I argue that `std::vector<char>`, `MyStruct`, `Point *`, `float`, and `int` can all be instantiated.
strager
Question on the issue: http://stackoverflow.com/questions/1745487/what-can-be-instantiated
strager
Judging by your response on that issue and the bit quoted, the standard would seem to suggest that the array is a single instance (allocated by new) and the Point* slots within the array are still NOT instances ;-). I'm a POD!=instance kinda guy.
Andy Dent
Equal rights for PODs! :-)
James McNellis
+1  A: 

no initialisation takes place in C++ with such a statement

The Point* objects in array are zero-initialized if array is global.

Fred
But why would anyone have a global array in a non-C environment (and even then globals might be avoided)
laura
good point. The precise wording (from C++ Programming Language sec 9.4.1) is "nonlocal variables...variables defined outside any function...by default initialised to the default for its type."
Andy Dent