C++ - What does this double pointer/array structure really mean? I have trouble picturing it
This is within C++ code
YInterface ** Y_list;
int numberofYInterfaces;
then
numberofYInterfaces=1;
Y_list = new YInterface *[numberofYInterfaces]; //What ??????
I have a very hard time picturing the structure of Y_list? And then imagine my confusion when and if the numberofYInterfaces becomes more than one, even 2?
OOPS sorry and I forgot to write this below statement:
Y_list[i]= new AnotherCla开发者_如何学Goss();
//later addition to my orginal question . Thanks for the headsup Eric Fortin. Note: AnotherClass is inherited from YInterface.
Any help is appreciated
When you declare Y_list
, you get a single variable with an unspecified value in it:
Y_list +-------+ | | +-------+
When you assign it with new[]
, it points to whatever new[]
allocated, which in this case is an array of pointers:
Y_list array +-------+ +-------+ | o---+---->| | +-------+ +-------+ | | +-------+ | | +-------+ | | +-------+ | | +-------+
At that point, you don't yet have any YInterface
objects. You just have space allocated to hold pointers to them, should they ever exist.
Finally, you assign a value to one of the elements Y_list[i] = new AnotherClass
. That's when a YInterface
descendant exists, but you only have one so far. Run that code in a loop and you'll get multiple instances. But you still just have one array, and one pointer to that array.
Y_list array AnotherClass +-------+ +-------+ +-------+ | o---+---->| o---+---->| | +-------+ +-------+ | | | | | | +-------+ | | | | | | +-------+ +-------+ | | +-------+ | | +-------+
To free all this, remember to have one delete
statement for each new
statement you had, and one delete[]
for each new[]
:
delete Y_list[i];
delete[] Y_list;
Y_list points to a chunk of memory which is an array of pointers to YInterface objects -- each pointer is sizeof (YInterface *), so this chunk of memory (after the call to new) is of size numberOfYInterfaces * sizeof (YInterface *).
So Y_list is just a normal dynamically allocated array, with numberOfYInterfaces elements, each of which is itself a pointer to a YInterface object.
It means it's a dynamically allocated array of pointers on YInterface. Then suppose method blah is part of YInterface, you could access it through the array like:
Y_list[0]->blah();
Concerning your edit. Every item in the array is a pointer on YInterface so to actually have something pointed to, you need to allocate it which you do with new
operator. So doing Y_list[i] = new AnotherClass()
does allocate an AnotherClass object and store a pointer on this object in the array at index i.
Keep in mind though that AnotherClass needs to inherit YInterface for this to work.
in c++ array are pointers , that is the memory address of first element of array is the name of array , so now what you have is array of pointers , hence **
精彩评论