This question may be a little bit self-explanatory for some of you but I am really trying to understand what are the similarities between: List myList = new ArrayList<Vertex>(); { In JAVA } and Vertex* myList = new Vertex[size] {In C++}. What's the point of that * in C++ that does not exist in Java. I know that it points to the first element of the list..when are we supposed to use *? Is it just for vectors or?
1 Answer
We cannot talk about similarities/differences when these two languages have different assumptions.
In Java everything is a reference - you are creating objects, they are being stored somewhere (on stack/heap) but you are accessing them only by reference. That means that in myList there will be address kept for the ArrayList instance (real instance - in memory)
In C++ you can access object as objects (with all after-effects like copying whole object when passing as argument to function) but also by reference (using pointers - just to avoid such after-effects but also to use some special gifts given to pointers like iterating over memory cells).
Yeah - about iterating over computer memory - the funny fact in C++ is that it's allocating solid block of memory (I mean - next N cells/addresses in row) to put array there - that's why you can declare your array as
int* a = new int[100]; // this is called dynamic allocation because what you need is the address of the first element, and the object size (given by pointer type). You can jump to the next element simply by doing
a++ To differ using object/pointer you need (or do not need) asterix operator * and that's why it occurs in C++.
read also What exactly is the purpose of the (asterisk) in pointers?
5 Comments
int a[100]) it still will be sent to functions and kept under a variable as pointer the the first element - that limitation is because of performance (try to imagine copying 1mln elements on function call). Of course dereffered array element like a[100] or a++ is an object unless you are keeping another pointers in array - why notint a[100] c++ has to copy that for me into a pointer variable int* a which is means extra work?
Vertex* myList = new Vertex[size]has been replaced bystd::vector<Vertex> myList(size). Sounds like you could use a good C++ bookArrayListis like an array. They are two very different things.*: although we tend to writeVertex* myList, the original intent was to writeVertex *myList, to mean that "the type of*myListisVertex". Since*dereferences a pointer type to its type, this means thatmyListis a pointer to aVertex. It's a bit roundabout, but that is, apparently, where the notation arose.