开发者

C++ Classes - Pointers question

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 ju开发者_如何转开发st one because when the compiler sees Point* it just creates one instance as a base.


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.


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.


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.


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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜